expand.c revision 178631
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 178631 2008-04-28 07:26:34Z stefanf $");
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 nulonly;		/* 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(char *, 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:
275			return (startp);
276		case CTLQUOTEMARK:
277			return (startp);
278		case ':':
279			if (flag & EXP_VARTILDE)
280				goto done;
281			break;
282		case '/':
283			goto done;
284		}
285		p++;
286	}
287done:
288	*p = '\0';
289	if (*(startp+1) == '\0') {
290		if ((home = lookupvar("HOME")) == NULL)
291			goto lose;
292	} else {
293		if ((pw = getpwnam(startp+1)) == NULL)
294			goto lose;
295		home = pw->pw_dir;
296	}
297	if (*home == '\0')
298		goto lose;
299	*p = c;
300	while ((c = *home++) != '\0') {
301		if (quotes && SQSYNTAX[(int)c] == CCTL)
302			STPUTC(CTLESC, expdest);
303		STPUTC(c, expdest);
304	}
305	return (p);
306lose:
307	*p = c;
308	return (startp);
309}
310
311
312STATIC void
313removerecordregions(int endoff)
314{
315	if (ifslastp == NULL)
316		return;
317
318	if (ifsfirst.endoff > endoff) {
319		while (ifsfirst.next != NULL) {
320			struct ifsregion *ifsp;
321			INTOFF;
322			ifsp = ifsfirst.next->next;
323			ckfree(ifsfirst.next);
324			ifsfirst.next = ifsp;
325			INTON;
326		}
327		if (ifsfirst.begoff > endoff)
328			ifslastp = NULL;
329		else {
330			ifslastp = &ifsfirst;
331			ifsfirst.endoff = endoff;
332		}
333		return;
334	}
335
336	ifslastp = &ifsfirst;
337	while (ifslastp->next && ifslastp->next->begoff < endoff)
338		ifslastp=ifslastp->next;
339	while (ifslastp->next != NULL) {
340		struct ifsregion *ifsp;
341		INTOFF;
342		ifsp = ifslastp->next->next;
343		ckfree(ifslastp->next);
344		ifslastp->next = ifsp;
345		INTON;
346	}
347	if (ifslastp->endoff > endoff)
348		ifslastp->endoff = endoff;
349}
350
351/*
352 * Expand arithmetic expression.  Backup to start of expression,
353 * evaluate, place result in (backed up) result, adjust string position.
354 */
355void
356expari(int flag)
357{
358	char *p, *start;
359	arith_t result;
360	int begoff;
361	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
362	int quoted;
363
364
365	/*
366	 * This routine is slightly over-complicated for
367	 * efficiency.  First we make sure there is
368	 * enough space for the result, which may be bigger
369	 * than the expression if we add exponentiation.  Next we
370	 * scan backwards looking for the start of arithmetic.  If the
371	 * next previous character is a CTLESC character, then we
372	 * have to rescan starting from the beginning since CTLESC
373	 * characters have to be processed left to right.
374	 */
375	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
376	USTPUTC('\0', expdest);
377	start = stackblock();
378	p = expdest - 2;
379	while (p >= start && *p != CTLARI)
380		--p;
381	if (p < start || *p != CTLARI)
382		error("missing CTLARI (shouldn't happen)");
383	if (p > start && *(p - 1) == CTLESC)
384		for (p = start; *p != CTLARI; p++)
385			if (*p == CTLESC)
386				p++;
387
388	if (p[1] == '"')
389		quoted=1;
390	else
391		quoted=0;
392	begoff = p - start;
393	removerecordregions(begoff);
394	if (quotes)
395		rmescapes(p+2);
396	result = arith(p+2);
397	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
398	while (*p++)
399		;
400	if (quoted == 0)
401		recordregion(begoff, p - 1 - start, 0);
402	result = expdest - p + 1;
403	STADJUST(-result, expdest);
404}
405
406
407/*
408 * Expand stuff in backwards quotes.
409 */
410
411STATIC void
412expbackq(union node *cmd, int quoted, int flag)
413{
414	struct backcmd in;
415	int i;
416	char buf[128];
417	char *p;
418	char *dest = expdest;
419	struct ifsregion saveifs, *savelastp;
420	struct nodelist *saveargbackq;
421	char lastc;
422	int startloc = dest - stackblock();
423	char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
424	int saveherefd;
425	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
426	int nnl;
427
428	INTOFF;
429	saveifs = ifsfirst;
430	savelastp = ifslastp;
431	saveargbackq = argbackq;
432	saveherefd = herefd;
433	herefd = -1;
434	p = grabstackstr(dest);
435	evalbackcmd(cmd, &in);
436	ungrabstackstr(p, dest);
437	ifsfirst = saveifs;
438	ifslastp = savelastp;
439	argbackq = saveargbackq;
440	herefd = saveherefd;
441
442	p = in.buf;
443	lastc = '\0';
444	nnl = 0;
445	/* Don't copy trailing newlines */
446	for (;;) {
447		if (--in.nleft < 0) {
448			if (in.fd < 0)
449				break;
450			while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
451			TRACE(("expbackq: read returns %d\n", i));
452			if (i <= 0)
453				break;
454			p = buf;
455			in.nleft = i - 1;
456		}
457		lastc = *p++;
458		if (lastc != '\0') {
459			if (quotes && syntax[(int)lastc] == CCTL)
460				STPUTC(CTLESC, dest);
461			if (lastc == '\n') {
462				nnl++;
463			} else {
464				while (nnl > 0) {
465					nnl--;
466					STPUTC('\n', dest);
467				}
468				STPUTC(lastc, dest);
469			}
470		}
471	}
472
473	if (in.fd >= 0)
474		close(in.fd);
475	if (in.buf)
476		ckfree(in.buf);
477	if (in.jp)
478		exitstatus = waitforjob(in.jp, (int *)NULL);
479	if (quoted == 0)
480		recordregion(startloc, dest - stackblock(), 0);
481	TRACE(("evalbackq: size=%d: \"%.*s\"\n",
482		(dest - stackblock()) - startloc,
483		(dest - stackblock()) - startloc,
484		stackblock() + startloc));
485	expdest = dest;
486	INTON;
487}
488
489
490
491STATIC int
492subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
493  int varflags)
494{
495	char *startp;
496	char *loc = NULL;
497	char *q;
498	int c = 0;
499	int saveherefd = herefd;
500	struct nodelist *saveargbackq = argbackq;
501	int amount;
502
503	herefd = -1;
504	argstr(p, 0);
505	STACKSTRNUL(expdest);
506	herefd = saveherefd;
507	argbackq = saveargbackq;
508	startp = stackblock() + startloc;
509	if (str == NULL)
510	    str = stackblock() + strloc;
511
512	switch (subtype) {
513	case VSASSIGN:
514		setvar(str, startp, 0);
515		amount = startp - expdest;
516		STADJUST(amount, expdest);
517		varflags &= ~VSNUL;
518		if (c != 0)
519			*loc = c;
520		return 1;
521
522	case VSQUESTION:
523		if (*p != CTLENDVAR) {
524			outfmt(&errout, "%s\n", startp);
525			error((char *)NULL);
526		}
527		error("%.*s: parameter %snot set", (int)(p - str - 1),
528		      str, (varflags & VSNUL) ? "null or "
529					      : nullstr);
530		return 0;
531
532	case VSTRIMLEFT:
533		for (loc = startp; loc < str; loc++) {
534			c = *loc;
535			*loc = '\0';
536			if (patmatch(str, startp, varflags & VSQUOTE)) {
537				*loc = c;
538				goto recordleft;
539			}
540			*loc = c;
541			if ((varflags & VSQUOTE) && *loc == CTLESC)
542				loc++;
543		}
544		return 0;
545
546	case VSTRIMLEFTMAX:
547		for (loc = str - 1; loc >= startp;) {
548			c = *loc;
549			*loc = '\0';
550			if (patmatch(str, startp, varflags & VSQUOTE)) {
551				*loc = c;
552				goto recordleft;
553			}
554			*loc = c;
555			loc--;
556			if ((varflags & VSQUOTE) && loc > startp &&
557			    *(loc - 1) == CTLESC) {
558				for (q = startp; q < loc; q++)
559					if (*q == CTLESC)
560						q++;
561				if (q > loc)
562					loc--;
563			}
564		}
565		return 0;
566
567	case VSTRIMRIGHT:
568		for (loc = str - 1; loc >= startp;) {
569			if (patmatch(str, loc, varflags & VSQUOTE)) {
570				amount = loc - expdest;
571				STADJUST(amount, expdest);
572				return 1;
573			}
574			loc--;
575			if ((varflags & VSQUOTE) && loc > startp &&
576			    *(loc - 1) == CTLESC) {
577				for (q = startp; q < loc; q++)
578					if (*q == CTLESC)
579						q++;
580				if (q > loc)
581					loc--;
582			}
583		}
584		return 0;
585
586	case VSTRIMRIGHTMAX:
587		for (loc = startp; loc < str - 1; loc++) {
588			if (patmatch(str, loc, varflags & VSQUOTE)) {
589				amount = loc - expdest;
590				STADJUST(amount, expdest);
591				return 1;
592			}
593			if ((varflags & VSQUOTE) && *loc == CTLESC)
594				loc++;
595		}
596		return 0;
597
598
599	default:
600		abort();
601	}
602
603recordleft:
604	amount = ((str - 1) - (loc - startp)) - expdest;
605	STADJUST(amount, expdest);
606	while (loc != str - 1)
607		*startp++ = *loc++;
608	return 1;
609}
610
611
612/*
613 * Expand a variable, and return a pointer to the next character in the
614 * input string.
615 */
616
617STATIC char *
618evalvar(char *p, int flag)
619{
620	int subtype;
621	int varflags;
622	char *var;
623	char *val;
624	int patloc;
625	int c;
626	int set;
627	int special;
628	int startloc;
629	int varlen;
630	int easy;
631	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
632
633	varflags = (unsigned char)*p++;
634	subtype = varflags & VSTYPE;
635	var = p;
636	special = 0;
637	if (! is_name(*p))
638		special = 1;
639	p = strchr(p, '=') + 1;
640again: /* jump here after setting a variable with ${var=text} */
641	if (special) {
642		set = varisset(var, varflags & VSNUL);
643		val = NULL;
644	} else {
645		val = bltinlookup(var, 1);
646		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
647			val = NULL;
648			set = 0;
649		} else
650			set = 1;
651	}
652	varlen = 0;
653	startloc = expdest - stackblock();
654	if (!set && uflag) {
655		switch (subtype) {
656		case VSNORMAL:
657		case VSTRIMLEFT:
658		case VSTRIMLEFTMAX:
659		case VSTRIMRIGHT:
660		case VSTRIMRIGHTMAX:
661		case VSLENGTH:
662			error("%.*s: parameter not set", (int)(p - var - 1),
663			    var);
664		}
665	}
666	if (set && subtype != VSPLUS) {
667		/* insert the value of the variable */
668		if (special) {
669			varvalue(var, varflags & VSQUOTE, subtype, flag);
670			if (subtype == VSLENGTH) {
671				varlen = expdest - stackblock() - startloc;
672				STADJUST(-varlen, expdest);
673			}
674		} else {
675			char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
676								  : BASESYNTAX;
677
678			if (subtype == VSLENGTH) {
679				for (;*val; val++)
680					varlen++;
681			}
682			else {
683				while (*val) {
684					if (quotes &&
685					    syntax[(int)*val] == CCTL)
686						STPUTC(CTLESC, expdest);
687					STPUTC(*val++, expdest);
688				}
689
690			}
691		}
692	}
693
694	if (subtype == VSPLUS)
695		set = ! set;
696
697	easy = ((varflags & VSQUOTE) == 0 ||
698		(*var == '@' && shellparam.nparam != 1));
699
700
701	switch (subtype) {
702	case VSLENGTH:
703		expdest = cvtnum(varlen, expdest);
704		goto record;
705
706	case VSNORMAL:
707		if (!easy)
708			break;
709record:
710		recordregion(startloc, expdest - stackblock(),
711			     varflags & VSQUOTE);
712		break;
713
714	case VSPLUS:
715	case VSMINUS:
716		if (!set) {
717			argstr(p, flag);
718			break;
719		}
720		if (easy)
721			goto record;
722		break;
723
724	case VSTRIMLEFT:
725	case VSTRIMLEFTMAX:
726	case VSTRIMRIGHT:
727	case VSTRIMRIGHTMAX:
728		if (!set)
729			break;
730		/*
731		 * Terminate the string and start recording the pattern
732		 * right after it
733		 */
734		STPUTC('\0', expdest);
735		patloc = expdest - stackblock();
736		if (subevalvar(p, NULL, patloc, subtype,
737			       startloc, varflags) == 0) {
738			int amount = (expdest - stackblock() - patloc) + 1;
739			STADJUST(-amount, expdest);
740		}
741		/* Remove any recorded regions beyond start of variable */
742		removerecordregions(startloc);
743		goto record;
744
745	case VSASSIGN:
746	case VSQUESTION:
747		if (!set) {
748			if (subevalvar(p, var, 0, subtype, startloc, varflags)) {
749				varflags &= ~VSNUL;
750				/*
751				 * Remove any recorded regions beyond
752				 * start of variable
753				 */
754				removerecordregions(startloc);
755				goto again;
756			}
757			break;
758		}
759		if (easy)
760			goto record;
761		break;
762
763	case VSERROR:
764		c = p - var - 1;
765		error("${%.*s%s}: Bad substitution", c, var,
766		    (c > 0 && *p != CTLENDVAR) ? "..." : "");
767
768	default:
769		abort();
770	}
771
772	if (subtype != VSNORMAL) {	/* skip to end of alternative */
773		int nesting = 1;
774		for (;;) {
775			if ((c = *p++) == CTLESC)
776				p++;
777			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
778				if (set)
779					argbackq = argbackq->next;
780			} else if (c == CTLVAR) {
781				if ((*p++ & VSTYPE) != VSNORMAL)
782					nesting++;
783			} else if (c == CTLENDVAR) {
784				if (--nesting == 0)
785					break;
786			}
787		}
788	}
789	return p;
790}
791
792
793
794/*
795 * Test whether a specialized variable is set.
796 */
797
798STATIC int
799varisset(char *name, int nulok)
800{
801
802	if (*name == '!')
803		return backgndpid != -1;
804	else if (*name == '@' || *name == '*') {
805		if (*shellparam.p == NULL)
806			return 0;
807
808		if (nulok) {
809			char **av;
810
811			for (av = shellparam.p; *av; av++)
812				if (**av != '\0')
813					return 1;
814			return 0;
815		}
816	} else if (is_digit(*name)) {
817		char *ap;
818		int num = atoi(name);
819
820		if (num > shellparam.nparam)
821			return 0;
822
823		if (num == 0)
824			ap = arg0;
825		else
826			ap = shellparam.p[num - 1];
827
828		if (nulok && (ap == NULL || *ap == '\0'))
829			return 0;
830	}
831	return 1;
832}
833
834
835
836/*
837 * Add the value of a specialized variable to the stack string.
838 */
839
840STATIC void
841varvalue(char *name, int quoted, int subtype, int flag)
842{
843	int num;
844	char *p;
845	int i;
846	extern int oexitstatus;
847	char sep;
848	char **ap;
849	char const *syntax;
850
851#define STRTODEST(p) \
852	do {\
853	if (flag & (EXP_FULL | EXP_CASE) && subtype != VSLENGTH) { \
854		syntax = quoted? DQSYNTAX : BASESYNTAX; \
855		while (*p) { \
856			if (syntax[(int)*p] == CCTL) \
857				STPUTC(CTLESC, expdest); \
858			STPUTC(*p++, expdest); \
859		} \
860	} else \
861		while (*p) \
862			STPUTC(*p++, expdest); \
863	} while (0)
864
865
866	switch (*name) {
867	case '$':
868		num = rootpid;
869		goto numvar;
870	case '?':
871		num = oexitstatus;
872		goto numvar;
873	case '#':
874		num = shellparam.nparam;
875		goto numvar;
876	case '!':
877		num = backgndpid;
878numvar:
879		expdest = cvtnum(num, expdest);
880		break;
881	case '-':
882		for (i = 0 ; i < NOPTS ; i++) {
883			if (optlist[i].val)
884				STPUTC(optlist[i].letter, expdest);
885		}
886		break;
887	case '@':
888		if (flag & EXP_FULL && quoted) {
889			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
890				STRTODEST(p);
891				if (*ap)
892					STPUTC('\0', expdest);
893			}
894			break;
895		}
896		/* FALLTHROUGH */
897	case '*':
898		if (ifsset())
899			sep = ifsval()[0];
900		else
901			sep = ' ';
902		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
903			STRTODEST(p);
904			if (*ap && sep)
905				STPUTC(sep, expdest);
906		}
907		break;
908	case '0':
909		p = arg0;
910		STRTODEST(p);
911		break;
912	default:
913		if (is_digit(*name)) {
914			num = atoi(name);
915			if (num > 0 && num <= shellparam.nparam) {
916				p = shellparam.p[num - 1];
917				STRTODEST(p);
918			}
919		}
920		break;
921	}
922}
923
924
925
926/*
927 * Record the the fact that we have to scan this region of the
928 * string for IFS characters.
929 */
930
931STATIC void
932recordregion(int start, int end, int nulonly)
933{
934	struct ifsregion *ifsp;
935
936	if (ifslastp == NULL) {
937		ifsp = &ifsfirst;
938	} else {
939		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
940		ifslastp->next = ifsp;
941	}
942	ifslastp = ifsp;
943	ifslastp->next = NULL;
944	ifslastp->begoff = start;
945	ifslastp->endoff = end;
946	ifslastp->nulonly = nulonly;
947}
948
949
950
951/*
952 * Break the argument string into pieces based upon IFS and add the
953 * strings to the argument list.  The regions of the string to be
954 * searched for IFS characters have been stored by recordregion.
955 */
956STATIC void
957ifsbreakup(char *string, struct arglist *arglist)
958{
959	struct ifsregion *ifsp;
960	struct strlist *sp;
961	char *start;
962	char *p;
963	char *q;
964	char *ifs;
965	int ifsspc;
966	int nulonly;
967
968
969	start = string;
970	ifsspc = 0;
971	nulonly = 0;
972	if (ifslastp != NULL) {
973		ifsp = &ifsfirst;
974		do {
975			p = string + ifsp->begoff;
976			nulonly = ifsp->nulonly;
977			ifs = nulonly ? nullstr :
978				( ifsset() ? ifsval() : " \t\n" );
979			ifsspc = 0;
980			while (p < string + ifsp->endoff) {
981				q = p;
982				if (*p == CTLESC)
983					p++;
984				if (strchr(ifs, *p)) {
985					if (!nulonly)
986						ifsspc = (strchr(" \t\n", *p) != NULL);
987					/* Ignore IFS whitespace at start */
988					if (q == start && ifsspc) {
989						p++;
990						start = p;
991						continue;
992					}
993					*q = '\0';
994					sp = (struct strlist *)stalloc(sizeof *sp);
995					sp->text = start;
996					*arglist->lastp = sp;
997					arglist->lastp = &sp->next;
998					p++;
999					if (!nulonly) {
1000						for (;;) {
1001							if (p >= string + ifsp->endoff) {
1002								break;
1003							}
1004							q = p;
1005							if (*p == CTLESC)
1006								p++;
1007							if (strchr(ifs, *p) == NULL ) {
1008								p = q;
1009								break;
1010							} else if (strchr(" \t\n",*p) == NULL) {
1011								if (ifsspc) {
1012									p++;
1013									ifsspc = 0;
1014								} else {
1015									p = q;
1016									break;
1017								}
1018							} else
1019								p++;
1020						}
1021					}
1022					start = p;
1023				} else
1024					p++;
1025			}
1026		} while ((ifsp = ifsp->next) != NULL);
1027		if (*start || (!ifsspc && start > string)) {
1028			sp = (struct strlist *)stalloc(sizeof *sp);
1029			sp->text = start;
1030			*arglist->lastp = sp;
1031			arglist->lastp = &sp->next;
1032		}
1033	} else {
1034		sp = (struct strlist *)stalloc(sizeof *sp);
1035		sp->text = start;
1036		*arglist->lastp = sp;
1037		arglist->lastp = &sp->next;
1038	}
1039}
1040
1041
1042
1043/*
1044 * Expand shell metacharacters.  At this point, the only control characters
1045 * should be escapes.  The results are stored in the list exparg.
1046 */
1047
1048STATIC char *expdir;
1049
1050
1051STATIC void
1052expandmeta(struct strlist *str, int flag __unused)
1053{
1054	char *p;
1055	struct strlist **savelastp;
1056	struct strlist *sp;
1057	char c;
1058	/* TODO - EXP_REDIR */
1059
1060	while (str) {
1061		if (fflag)
1062			goto nometa;
1063		p = str->text;
1064		for (;;) {			/* fast check for meta chars */
1065			if ((c = *p++) == '\0')
1066				goto nometa;
1067			if (c == '*' || c == '?' || c == '[' || c == '!')
1068				break;
1069		}
1070		savelastp = exparg.lastp;
1071		INTOFF;
1072		if (expdir == NULL) {
1073			int i = strlen(str->text);
1074			expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
1075		}
1076
1077		expmeta(expdir, str->text);
1078		ckfree(expdir);
1079		expdir = NULL;
1080		INTON;
1081		if (exparg.lastp == savelastp) {
1082			/*
1083			 * no matches
1084			 */
1085nometa:
1086			*exparg.lastp = str;
1087			rmescapes(str->text);
1088			exparg.lastp = &str->next;
1089		} else {
1090			*exparg.lastp = NULL;
1091			*savelastp = sp = expsort(*savelastp);
1092			while (sp->next != NULL)
1093				sp = sp->next;
1094			exparg.lastp = &sp->next;
1095		}
1096		str = str->next;
1097	}
1098}
1099
1100
1101/*
1102 * Do metacharacter (i.e. *, ?, [...]) expansion.
1103 */
1104
1105STATIC void
1106expmeta(char *enddir, char *name)
1107{
1108	char *p;
1109	char *q;
1110	char *start;
1111	char *endname;
1112	int metaflag;
1113	struct stat statb;
1114	DIR *dirp;
1115	struct dirent *dp;
1116	int atend;
1117	int matchdot;
1118
1119	metaflag = 0;
1120	start = name;
1121	for (p = name ; ; p++) {
1122		if (*p == '*' || *p == '?')
1123			metaflag = 1;
1124		else if (*p == '[') {
1125			q = p + 1;
1126			if (*q == '!' || *q == '^')
1127				q++;
1128			for (;;) {
1129				while (*q == CTLQUOTEMARK)
1130					q++;
1131				if (*q == CTLESC)
1132					q++;
1133				if (*q == '/' || *q == '\0')
1134					break;
1135				if (*++q == ']') {
1136					metaflag = 1;
1137					break;
1138				}
1139			}
1140		} else if (*p == '!' && p[1] == '!'	&& (p == name || p[-1] == '/')) {
1141			metaflag = 1;
1142		} else if (*p == '\0')
1143			break;
1144		else if (*p == CTLQUOTEMARK)
1145			continue;
1146		else if (*p == CTLESC)
1147			p++;
1148		if (*p == '/') {
1149			if (metaflag)
1150				break;
1151			start = p + 1;
1152		}
1153	}
1154	if (metaflag == 0) {	/* we've reached the end of the file name */
1155		if (enddir != expdir)
1156			metaflag++;
1157		for (p = name ; ; p++) {
1158			if (*p == CTLQUOTEMARK)
1159				continue;
1160			if (*p == CTLESC)
1161				p++;
1162			*enddir++ = *p;
1163			if (*p == '\0')
1164				break;
1165		}
1166		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
1167			addfname(expdir);
1168		return;
1169	}
1170	endname = p;
1171	if (start != name) {
1172		p = name;
1173		while (p < start) {
1174			while (*p == CTLQUOTEMARK)
1175				p++;
1176			if (*p == CTLESC)
1177				p++;
1178			*enddir++ = *p++;
1179		}
1180	}
1181	if (enddir == expdir) {
1182		p = ".";
1183	} else if (enddir == expdir + 1 && *expdir == '/') {
1184		p = "/";
1185	} else {
1186		p = expdir;
1187		enddir[-1] = '\0';
1188	}
1189	if ((dirp = opendir(p)) == NULL)
1190		return;
1191	if (enddir != expdir)
1192		enddir[-1] = '/';
1193	if (*endname == 0) {
1194		atend = 1;
1195	} else {
1196		atend = 0;
1197		*endname++ = '\0';
1198	}
1199	matchdot = 0;
1200	p = start;
1201	while (*p == CTLQUOTEMARK)
1202		p++;
1203	if (*p == CTLESC)
1204		p++;
1205	if (*p == '.')
1206		matchdot++;
1207	while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1208		if (dp->d_name[0] == '.' && ! matchdot)
1209			continue;
1210		if (patmatch(start, dp->d_name, 0)) {
1211			if (atend) {
1212				scopy(dp->d_name, enddir);
1213				addfname(expdir);
1214			} else {
1215				for (p = enddir, q = dp->d_name;
1216				     (*p++ = *q++) != '\0';)
1217					continue;
1218				p[-1] = '/';
1219				expmeta(p, endname);
1220			}
1221		}
1222	}
1223	closedir(dirp);
1224	if (! atend)
1225		endname[-1] = '/';
1226}
1227
1228
1229/*
1230 * Add a file name to the list.
1231 */
1232
1233STATIC void
1234addfname(char *name)
1235{
1236	char *p;
1237	struct strlist *sp;
1238
1239	p = stalloc(strlen(name) + 1);
1240	scopy(name, p);
1241	sp = (struct strlist *)stalloc(sizeof *sp);
1242	sp->text = p;
1243	*exparg.lastp = sp;
1244	exparg.lastp = &sp->next;
1245}
1246
1247
1248/*
1249 * Sort the results of file name expansion.  It calculates the number of
1250 * strings to sort and then calls msort (short for merge sort) to do the
1251 * work.
1252 */
1253
1254STATIC struct strlist *
1255expsort(struct strlist *str)
1256{
1257	int len;
1258	struct strlist *sp;
1259
1260	len = 0;
1261	for (sp = str ; sp ; sp = sp->next)
1262		len++;
1263	return msort(str, len);
1264}
1265
1266
1267STATIC struct strlist *
1268msort(struct strlist *list, int len)
1269{
1270	struct strlist *p, *q = NULL;
1271	struct strlist **lpp;
1272	int half;
1273	int n;
1274
1275	if (len <= 1)
1276		return list;
1277	half = len >> 1;
1278	p = list;
1279	for (n = half ; --n >= 0 ; ) {
1280		q = p;
1281		p = p->next;
1282	}
1283	q->next = NULL;			/* terminate first half of list */
1284	q = msort(list, half);		/* sort first half of list */
1285	p = msort(p, len - half);		/* sort second half */
1286	lpp = &list;
1287	for (;;) {
1288		if (strcmp(p->text, q->text) < 0) {
1289			*lpp = p;
1290			lpp = &p->next;
1291			if ((p = *lpp) == NULL) {
1292				*lpp = q;
1293				break;
1294			}
1295		} else {
1296			*lpp = q;
1297			lpp = &q->next;
1298			if ((q = *lpp) == NULL) {
1299				*lpp = p;
1300				break;
1301			}
1302		}
1303	}
1304	return list;
1305}
1306
1307
1308
1309/*
1310 * Returns true if the pattern matches the string.
1311 */
1312
1313int
1314patmatch(char *pattern, char *string, int squoted)
1315{
1316#ifdef notdef
1317	if (pattern[0] == '!' && pattern[1] == '!')
1318		return 1 - pmatch(pattern + 2, string);
1319	else
1320#endif
1321		return pmatch(pattern, string, squoted);
1322}
1323
1324
1325STATIC int
1326pmatch(char *pattern, char *string, int squoted)
1327{
1328	char *p, *q;
1329	char c;
1330
1331	p = pattern;
1332	q = string;
1333	for (;;) {
1334		switch (c = *p++) {
1335		case '\0':
1336			goto breakloop;
1337		case CTLESC:
1338			if (squoted && *q == CTLESC)
1339				q++;
1340			if (*q++ != *p++)
1341				return 0;
1342			break;
1343		case CTLQUOTEMARK:
1344			continue;
1345		case '?':
1346			if (squoted && *q == CTLESC)
1347				q++;
1348			if (*q++ == '\0')
1349				return 0;
1350			break;
1351		case '*':
1352			c = *p;
1353			while (c == CTLQUOTEMARK || c == '*')
1354				c = *++p;
1355			if (c != CTLESC &&  c != CTLQUOTEMARK &&
1356			    c != '?' && c != '*' && c != '[') {
1357				while (*q != c) {
1358					if (squoted && *q == CTLESC &&
1359					    q[1] == c)
1360						break;
1361					if (*q == '\0')
1362						return 0;
1363					if (squoted && *q == CTLESC)
1364						q++;
1365					q++;
1366				}
1367			}
1368			do {
1369				if (pmatch(p, q, squoted))
1370					return 1;
1371				if (squoted && *q == CTLESC)
1372					q++;
1373			} while (*q++ != '\0');
1374			return 0;
1375		case '[': {
1376			char *endp;
1377			int invert, found;
1378			char chr;
1379
1380			endp = p;
1381			if (*endp == '!' || *endp == '^')
1382				endp++;
1383			for (;;) {
1384				while (*endp == CTLQUOTEMARK)
1385					endp++;
1386				if (*endp == '\0')
1387					goto dft;		/* no matching ] */
1388				if (*endp == CTLESC)
1389					endp++;
1390				if (*++endp == ']')
1391					break;
1392			}
1393			invert = 0;
1394			if (*p == '!' || *p == '^') {
1395				invert++;
1396				p++;
1397			}
1398			found = 0;
1399			chr = *q++;
1400			if (squoted && chr == CTLESC)
1401				chr = *q++;
1402			if (chr == '\0')
1403				return 0;
1404			c = *p++;
1405			do {
1406				if (c == CTLQUOTEMARK)
1407					continue;
1408				if (c == CTLESC)
1409					c = *p++;
1410				if (*p == '-' && p[1] != ']') {
1411					p++;
1412					while (*p == CTLQUOTEMARK)
1413						p++;
1414					if (*p == CTLESC)
1415						p++;
1416					if (   collate_range_cmp(chr, c) >= 0
1417					    && collate_range_cmp(chr, *p) <= 0
1418					   )
1419						found = 1;
1420					p++;
1421				} else {
1422					if (chr == c)
1423						found = 1;
1424				}
1425			} while ((c = *p++) != ']');
1426			if (found == invert)
1427				return 0;
1428			break;
1429		}
1430dft:	        default:
1431			if (squoted && *q == CTLESC)
1432				q++;
1433			if (*q++ != c)
1434				return 0;
1435			break;
1436		}
1437	}
1438breakloop:
1439	if (*q != '\0')
1440		return 0;
1441	return 1;
1442}
1443
1444
1445
1446/*
1447 * Remove any CTLESC characters from a string.
1448 */
1449
1450void
1451rmescapes(char *str)
1452{
1453	char *p, *q;
1454
1455	p = str;
1456	while (*p != CTLESC && *p != CTLQUOTEMARK) {
1457		if (*p++ == '\0')
1458			return;
1459	}
1460	q = p;
1461	while (*p) {
1462		if (*p == CTLQUOTEMARK) {
1463			p++;
1464			continue;
1465		}
1466		if (*p == CTLESC)
1467			p++;
1468		*q++ = *p++;
1469	}
1470	*q = '\0';
1471}
1472
1473
1474
1475/*
1476 * See if a pattern matches in a case statement.
1477 */
1478
1479int
1480casematch(union node *pattern, char *val)
1481{
1482	struct stackmark smark;
1483	int result;
1484	char *p;
1485
1486	setstackmark(&smark);
1487	argbackq = pattern->narg.backquote;
1488	STARTSTACKSTR(expdest);
1489	ifslastp = NULL;
1490	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1491	STPUTC('\0', expdest);
1492	p = grabstackstr(expdest);
1493	result = patmatch(p, val, 0);
1494	popstackmark(&smark);
1495	return result;
1496}
1497
1498/*
1499 * Our own itoa().
1500 */
1501
1502STATIC char *
1503cvtnum(int num, char *buf)
1504{
1505	char temp[32];
1506	int neg = num < 0;
1507	char *p = temp + 31;
1508
1509	temp[31] = '\0';
1510
1511	do {
1512		*--p = num % 10 + '0';
1513	} while ((num /= 10) != 0);
1514
1515	if (neg)
1516		*--p = '-';
1517
1518	while (*p)
1519		STPUTC(*p++, buf);
1520	return buf;
1521}
1522
1523/*
1524 * Do most of the work for wordexp(3).
1525 */
1526
1527int
1528wordexpcmd(int argc, char **argv)
1529{
1530	size_t len;
1531	int i;
1532
1533	out1fmt("%08x", argc - 1);
1534	for (i = 1, len = 0; i < argc; i++)
1535		len += strlen(argv[i]);
1536	out1fmt("%08x", (int)len);
1537	for (i = 1; i < argc; i++) {
1538		out1str(argv[i]);
1539		out1c('\0');
1540	}
1541        return (0);
1542}
1543