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