Home | History | Annotate | Line # | Download | only in sh
      1 /*	$NetBSD: expand.c,v 1.153 2026/11/24 13:58:15 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)expand.c	8.5 (Berkeley) 5/15/95";
     39 #else
     40 __RCSID("$NetBSD: expand.c,v 1.153 2026/11/24 13:58:15 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <sys/types.h>
     45 #include <sys/time.h>
     46 #include <sys/stat.h>
     47 #include <errno.h>
     48 #include <dirent.h>
     49 #include <unistd.h>
     50 #include <pwd.h>
     51 #include <limits.h>
     52 #include <stdlib.h>
     53 #include <stdio.h>
     54 #include <wctype.h>
     55 #include <wchar.h>
     56 
     57 /*
     58  * Routines to expand arguments to commands.  We have to deal with
     59  * backquotes, shell variables, and file metacharacters.
     60  */
     61 
     62 #include "shell.h"
     63 #include "main.h"
     64 #include "nodes.h"
     65 #include "eval.h"
     66 #include "expand.h"
     67 #include "syntax.h"
     68 #include "arithmetic.h"
     69 #include "parser.h"
     70 #include "jobs.h"
     71 #include "options.h"
     72 #include "builtins.h"
     73 #include "var.h"
     74 #include "input.h"
     75 #include "output.h"
     76 #include "memalloc.h"
     77 #include "error.h"
     78 #include "mystring.h"
     79 #include "show.h"
     80 
     81 /*
     82  * Structure specifying which parts of the string should be searched
     83  * for IFS characters.
     84  */
     85 
     86 struct ifsregion {
     87 	struct ifsregion *next;	/* next region in list */
     88 	int begoff;		/* offset of start of region */
     89 	int endoff;		/* offset of end of region */
     90 	int inquotes;		/* search for nul bytes only */
     91 };
     92 
     93 
     94 char *expdest;			/* output of current string */
     95 struct nodelist *argbackq;	/* list of back quote expressions */
     96 struct ifsregion ifsfirst;	/* first struct in list of ifs regions */
     97 struct ifsregion *ifslastp;	/* last struct in list */
     98 struct arglist exparg;		/* holds expanded arg list */
     99 
    100 static int empty_dollar_at;	/* have expanded "$@" to nothing */
    101 
    102 STATIC const char *argstr(const char *, int);
    103 STATIC const char *exptilde(const char *, int);
    104 STATIC void expbackq(union node *, int, int);
    105 STATIC const char *expari(const char *);
    106 STATIC int subevalvar(const char *, const char *, int, int, int);
    107 STATIC int subevalvar_trim(const char *, int, int, int, int, int);
    108 STATIC const char *evalvar(const char *, int);
    109 STATIC int varisset(const char *, int);
    110 STATIC void varvalue(const char *, int, int, int);
    111 STATIC void recordregion(int, int, int);
    112 STATIC void removerecordregions(int);
    113 STATIC void ifsbreakup(char *, size_t, struct arglist *);
    114 STATIC void ifsfree(void);
    115 STATIC void expandmeta(struct strlist *, int);
    116 STATIC void expmeta(char *, char *);
    117 STATIC void addfname(char *);
    118 STATIC struct strlist *expsort(struct strlist *);
    119 STATIC struct strlist *msort(struct strlist *, int);
    120 STATIC int patmatch(const char *, const char *, int);
    121 STATIC char *cvtnum(int, char *);
    122 static int collate_range_cmp(wchar_t, wchar_t);
    123 STATIC void add_args(struct strlist *);
    124 STATIC void rmescapes_nl(char *);
    125 
    126 #ifdef	DEBUG
    127 static char *showchar(char *, char, int *);
    128 static char *showstr(const char *, int);
    129 #define	NULLTERM_4_TRACE(p)	STACKSTRNUL(p)
    130 #else
    131 #define	NULLTERM_4_TRACE(p)	do { /* nothing */ } while (0)
    132 #endif
    133 
    134 #define	IS_BORING(_ch)						\
    135 	((_ch) == CTLQUOTEMARK || (_ch) == CTLQUOTEEND || (_ch) == CTLNONL)
    136 #define	SKIP_BORING(p)						\
    137 	do {							\
    138 		char _ch;					\
    139 								\
    140 		while ((_ch = *(p)), IS_BORING(_ch))		\
    141 			(p)++;					\
    142 	} while (0)
    143 
    144 /*
    145  * Expand shell variables and backquotes inside a here document.
    146  */
    147 
    148 char *
    149 expandhere(union node *arg)
    150 {
    151 	int len;
    152 
    153 	VTRACE(DBG_EXPAND|DBG_REDIR, ("expandhere(%p)\n", arg));
    154 	expandarg(arg, NULL, 0);
    155 	len = rmescapes(stackblock());
    156 	VTRACE(DBG_EXPAND|DBG_REDIR, ("expandhere() -> %d\n", len));
    157 	return stalloc(len + 1);	/* include the \0 */
    158 }
    159 
    160 
    161 static int
    162 collate_range_cmp(wchar_t c1, wchar_t c2)
    163 {
    164 	wchar_t s1[2], s2[2];
    165 
    166 	s1[0] = c1;
    167 	s1[1] = L'\0';
    168 	s2[0] = c2;
    169 	s2[1] = L'\0';
    170 	return (wcscoll(s1, s2));
    171 }
    172 
    173 /*
    174  * Perform variable substitution and command substitution on an argument,
    175  * placing the resulting list of arguments in arglist.  If EXP_FULL is true,
    176  * perform splitting and file name expansion.  When arglist is NULL, perform
    177  * here document expansion.
    178  */
    179 
    180 void
    181 expandarg(union node *arg, struct arglist *arglist, int flag)
    182 {
    183 	struct strlist *sp;
    184 	char *p;
    185 	size_t len;
    186 
    187 	CTRACE(DBG_EXPAND, ("expandarg(fl=%#x)\n", flag));
    188 	if (fflag)		/* no filename expandsion */
    189 		flag &= ~EXP_GLOB;
    190 
    191 	empty_dollar_at = 0;
    192 	argbackq = arg->narg.backquote;
    193 	STARTSTACKSTR(expdest);
    194 	ifsfirst.next = NULL;
    195 	ifslastp = NULL;
    196 	line_number = arg->narg.lineno;
    197 	argstr(arg->narg.text, flag);
    198 	if (arglist == NULL) {
    199 		STACKSTRNUL(expdest);
    200 		DEBUG_ONLY(len = expdest - stackblock());
    201 		CTRACE(DBG_EXPAND,
    202 		    ("expandarg: no arglist, done[%d] (len %zu) \"%s\"\n",
    203 		    back_exitstatus, len, showstr(stackblock(), (int)len)));
    204 		return;			/* here document expanded */
    205 	}
    206 	STPUTC('\0', expdest);
    207 	len = expdest - stackblock() - 1;
    208 	CTRACE(DBG_EXPAND, ("expandarg: arglist got (%zu) \"%s\"\n",
    209 		    len, showstr(stackblock(), (int)len)));
    210 	p = grabstackstr(expdest);
    211 	exparg.lastp = &exparg.list;
    212 	/*
    213 	 * TODO - EXP_REDIR
    214 	 */
    215 	if (flag & EXP_SPLIT) {
    216 		ifsbreakup(p, len, &exparg);
    217 		*exparg.lastp = NULL;
    218 		exparg.lastp = &exparg.list;
    219 		if (flag & EXP_GLOB)
    220 			expandmeta(exparg.list, flag);
    221 		else
    222 			add_args(exparg.list);
    223 #if 0
    224 	} else if (flag & EXP_REDIR) {
    225 		/* if EXP_REDIR ever happens, it happens here */
    226 		/* for now just (below) remove escapes, and leave it alone */
    227 #endif
    228 	} else {
    229 		rmescapes(p);	/* we might have escaped CTL bytes to remove */
    230 		sp = stalloc(sizeof(*sp));
    231 		sp->text = p;
    232 		*exparg.lastp = sp;
    233 		exparg.lastp = &sp->next;
    234 	}
    235 	ifsfree();
    236 	*exparg.lastp = NULL;
    237 	if (exparg.list) {
    238 		*arglist->lastp = exparg.list;
    239 		arglist->lastp = exparg.lastp;
    240 	}
    241 }
    242 
    243 /*
    244  * Perform variable and command substitution.
    245  * If EXP_GLOB is set, output CTLESC characters to allow for further processing.
    246  * If EXP_SPLIT is set, remember location of result for later,
    247  * Otherwise treat $@ like $* since no splitting will be performed.
    248  */
    249 
    250 STATIC const char *
    251 argstr(const char *p, int flag)
    252 {
    253 	char c;
    254 	const int quotes = flag & EXP_QNEEDED;		/* do CTLESC */
    255 	int firsteq = 1;
    256 	int had_dol_at = 0;
    257 	int startoff;
    258 	const char *ifs = NULL;
    259 	int ifs_split = EXP_IFS_SPLIT;
    260 
    261 	if (flag & EXP_IFS_SPLIT)
    262 		ifs = ifsval();
    263 
    264 	CTRACE(DBG_EXPAND, ("argstr(\"%s\", %#x)%s\n",
    265 	    showstr(p, -1), flag, quotes ? " EXP_QNEEDED" : ""));
    266 
    267 	startoff = expdest - stackblock();
    268 	if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
    269 		p = exptilde(p, flag);
    270 	for (;;) {
    271 		switch (c = *p++) {
    272 		case '\0':
    273 			NULLTERM_4_TRACE(expdest);
    274 			VTRACE(DBG_EXPAND, ("argstr returning at \"\" "
    275 			   "added \"%s\" to expdest\n",
    276 			   showstr(stackblock(), expdest - stackblock())));
    277 			return p - 1;
    278 		case CTLENDVAR: /* end of expanding yyy in ${xxx-yyy} */
    279 		case CTLENDARI: /* end of a $(( )) string */
    280 			if (had_dol_at && *p == CTLQUOTEEND)
    281 				p++;
    282 			NULLTERM_4_TRACE(expdest);
    283 			VTRACE(DBG_EXPAND,
    284 			    ("argstr returning at %#x \"%.6s\"..."
    285 			    " after %2.2x; added \"%s\" to expdest\n",
    286 			    (*p & 0xFF), p, (c & 0xff),
    287 			    showstr(stackblock(), expdest - stackblock())));
    288 			return p;
    289 		case CTLQUOTEMARK:
    290 			/* "$@" syntax adherence hack */
    291 			if (p[0] == CTLVAR && p[1] & VSQUOTE &&
    292 			    p[2] == '@' && p[3] == '=') {
    293 				had_dol_at = 1;
    294 				break;
    295 			}
    296 			had_dol_at = 0;
    297 			empty_dollar_at = 0;
    298 			if ((flag & EXP_SPLIT) != 0)
    299 				STPUTC(c, expdest);
    300 			ifs_split = 0;
    301 			break;
    302 		case CTLNONL:
    303 			if (flag & EXP_NL)
    304 				STPUTC(c, expdest);
    305 			line_number++;
    306 			break;
    307 		case CTLCNL:
    308 			STPUTC('\n', expdest);	/* no line_number++ */
    309 			break;
    310 		case CTLQUOTEEND:
    311 			if (empty_dollar_at &&
    312 			    expdest - stackblock() > startoff &&
    313 			    expdest[-1] == CTLQUOTEMARK)
    314 				STUNPUTC(expdest);
    315 			else if (!had_dol_at && (flag & EXP_SPLIT) != 0)
    316 				STPUTC(c, expdest);
    317 			ifs_split = EXP_IFS_SPLIT;
    318 			had_dol_at = 0;
    319 			break;
    320 		case CTLESC:
    321 			if (quotes || ISCTL(*p))
    322 				STPUTC(c, expdest);
    323 			c = *p++;
    324 			STPUTC(c, expdest);
    325 			if (c == '\n')		/* should not happen, but ... */
    326 				line_number++;
    327 			break;
    328 		case CTLVAR: {
    329 			int xf = 0;
    330 			DEBUG_ONLY(unsigned int pos = expdest - stackblock());
    331 
    332 			NULLTERM_4_TRACE(expdest);
    333 			if (shellparam.nparam > 1) {
    334 				/*
    335 				 * Flags just in case we are expanding $* ($@)
    336 				 * in a field splitting context.  These are
    337 				 * irrelevant (unused) in all other cases.
    338 				 *
    339 				 * If there are 0 or 1 numeric params, then $*
    340 				 * should just vanish if $1 exists and is ""
    341 				 *
    342 				 * But for 2 or more params, we need to keep
    343 				 * "" first and last params, if our expansion
    344 				 * abuts other text (before or after)
    345 				 */
    346 				if (expdest != stackblock() &&
    347 				    expdest[-1] != '\0')
    348 					xf |= EXP_NEEDFIRST;	/* $* magic */
    349 				if (p[0] == VSNORMAL &&  /* p[2] == '=' && */
    350 				    (p[1] == '*' || p[1] == '@') &&
    351 				    p[3] != '\0')
    352 					xf |= EXP_NEEDLAST;	/* magic++ */
    353 			}
    354 
    355 			p = evalvar(p, (flag & ~EXP_IFS_SPLIT) |
    356 			    (flag & ifs_split) | xf);
    357 
    358 			NULLTERM_4_TRACE(expdest);
    359 			VTRACE(DBG_EXPAND, ("argstr evalvar "
    360 			   "added %zd \"%s\" to expdest\n",
    361 			   (size_t)(expdest - (stackblock() + pos)),
    362 			   showstr(stackblock() + pos,
    363 			     (int)(expdest - (stackblock() + pos)))));
    364 			break;
    365 		}
    366 		case CTLBACKQ:
    367 		case CTLBACKQ|CTLQUOTE: {
    368 			DEBUG_ONLY(unsigned int pos = expdest - stackblock());
    369 
    370 			if (flag & EXP_IN_QUOTES)
    371 				c |= CTLQUOTE;
    372 			expbackq(argbackq->n, c & CTLQUOTE, flag);
    373 			argbackq = argbackq->next;
    374 			NULLTERM_4_TRACE(expdest);
    375 			VTRACE(DBG_EXPAND, ("argstr expbackq added \"%s\" "
    376 			   "to expdest\n", showstr(stackblock() + pos,
    377 			     (int)(expdest - (stackblock() + pos)))));
    378 			break;
    379 		}
    380 		case CTLARI: {
    381 			DEBUG_ONLY(unsigned int pos = expdest - stackblock());
    382 
    383 			p = expari(p);
    384 			NULLTERM_4_TRACE(expdest);
    385 			VTRACE(DBG_EXPAND, ("argstr expari "
    386 			   "+ \"%s\" to expdest p=\"%.5s...\"\n",
    387 			   stackblock() + pos, p));
    388 			break;
    389 		}
    390 		case ':':
    391 		case '=':
    392 			/*
    393 			 * sort of a hack - expand tildes in variable
    394 			 * assignments (after the first '=' and after ':'s).
    395 			 */
    396 			STPUTC(c, expdest);
    397 			if (flag & ifs_split && strchr(ifs, c) != NULL) {
    398 				/* We need to get the output split here... */
    399 				recordregion(expdest - stackblock() - 1,
    400 						expdest - stackblock(), 0);
    401 			}
    402 			if (flag & EXP_VARTILDE && *p == '~') {
    403 				if (c == '=') {
    404 					if (firsteq)
    405 						firsteq = 0;
    406 					else
    407 						break;
    408 				}
    409 				p = exptilde(p, flag);
    410 			}
    411 			break;
    412 		default:
    413 			if (c == '\n')
    414 				line_number++;
    415 			STPUTC(c, expdest);
    416 			if (flag & ifs_split && strchr(ifs, c) != NULL) {
    417 				/* We need to get the output split here... */
    418 				recordregion(expdest - stackblock() - 1,
    419 						expdest - stackblock(), 0);
    420 			}
    421 			break;
    422 		}
    423 	}
    424 }
    425 
    426 STATIC const char *
    427 exptilde(const char *p, int flag)
    428 {
    429 	char c, last;
    430 	const char *startp = p;
    431 	struct passwd *pw;
    432 	const char *home;
    433 	const int quotes = flag & EXP_QNEEDED;
    434 	char *user;
    435 	struct stackmark smark;
    436 	DEBUG_ONLY(unsigned int offs = expdest - stackblock());
    437 
    438 	setstackmark(&smark);
    439 	(void) grabstackstr(expdest);
    440 	user = stackblock();		/* we will just borrow top of stack */
    441 
    442 	while ((c = *++p) != '\0') {
    443 		switch(c) {
    444 		case CTLESC:		/* any of these occurring */
    445 		case CTLVAR:		/* means ~ expansion */
    446 		case CTLBACKQ:		/* does not happen at all */
    447 		case CTLBACKQ | CTLQUOTE:
    448 		case CTLARI:		/* just leave original unchanged */
    449 		case CTLENDARI:
    450 		case CTLQUOTEMARK:
    451 		case '\n':
    452 			popstackmark(&smark);
    453 			return (startp);
    454 		case CTLNONL:
    455 			continue;
    456 		case ':':
    457 			if (!posix || flag & EXP_VARTILDE)
    458 				goto done;
    459 			break;
    460 		case CTLENDVAR:
    461 		case '/':
    462 			goto done;
    463 		}
    464 		STPUTC(c, user);
    465 	}
    466  done:;
    467 	STACKSTRNUL(user);
    468 	user = stackblock();		/* to start of collected username */
    469 
    470 	CTRACE(DBG_EXPAND, ("exptilde, found \"~%s\"", user));
    471 	if (*user == '\0') {
    472 		home = lookupvar("HOME");
    473 		/*
    474 		 * If HOME is unset, results are unspecified.
    475 		 * We used to just leave the ~ unchanged, but
    476 		 * (some) other shells do ... and this seems more useful.
    477 		 */
    478 		if (home == NULL && (pw = getpwuid(getuid())) != NULL)
    479 			home = pw->pw_dir;
    480 	} else if ((pw = getpwnam(user)) == NULL) {
    481 		/*
    482 		 * If user does not exist, results are undefined.
    483 		 * so we can abort() here if we want, but let's not!
    484 		 */
    485 		home = NULL;
    486 	} else
    487 		home = pw->pw_dir;
    488 
    489 	VTRACE(DBG_EXPAND, (" ->\"%s\"", home ? home : "<<NULL>>"));
    490 	popstackmark(&smark);	/* now expdest is valid again */
    491 
    492 	/*
    493 	 * Posix XCU 2.6.1: The value of $HOME (for ~) or the initial
    494 	 *		working directory from getpwnam() for ~user
    495 	 * Nothing there about "except if a null string".  So do what it wants.
    496 	 * In later drafts (to become Issue 8), it is even required that in
    497 	 * this case, (where HOME='') a bare ~ expands to "" (which must not
    498 	 * be reduced to nothing).
    499 	 */
    500 	last = '\0';		/* just in case *home == '\0' (already) */
    501 	if (home == NULL) {
    502 		CTRACE(DBG_EXPAND, (": returning unused \"%s\"\n", startp));
    503 		return startp;
    504 	}
    505 	while ((c = *home++) != '\0') {
    506 		/* The value must be quoted to prevent globbing */
    507 		if ((quotes && NEEDESC(c)) || ISCTL(c))
    508 			STPUTC(CTLESC, expdest);
    509 		STPUTC(c, expdest);
    510 		last = c;
    511 	}
    512 	/*
    513 	 * No need for special handling of empty strings,
    514 	 * the results from tilde expansions are not subject
    515 	 * to field splitting, so nothing that follows (in the
    516 	 * execution flow) will alter the data here, even an
    517 	 * empty string.
    518 	 */
    519 
    520 	/*
    521 	 * If HOME (or whatever) ended in a '/' (last == '/'), and
    522 	 * the ~prefix was terminated by a '/', then only keep one
    523 	 * of them - since we already took the one from HOME, just
    524 	 * skip over the one that ended the tilde prefix.
    525 	 *
    526 	 * Current (Issue 8) drafts say this is permitted, and recommend
    527 	 * it - a later version of the standard will probably require it.
    528 	 * This is to prevent ~/foo generating //foo when HOME=/ (and
    529 	 * other cases like it, but that's the important one).
    530 	 */
    531 	if (last == '/' && *p == '/')
    532 		p++;
    533 
    534 	CTRACE(DBG_EXPAND, (": added %d \"%.*s\" returning \"%s\"\n",
    535 	      expdest - stackblock() - offs, expdest - stackblock() - offs,
    536 	      stackblock() + offs, p));
    537 
    538 	return (p);
    539 }
    540 
    541 
    542 STATIC void
    543 removerecordregions(int endoff)
    544 {
    545 
    546 	VTRACE(DBG_EXPAND, ("removerecordregions(%d):", endoff));
    547 	if (ifslastp == NULL) {
    548 		VTRACE(DBG_EXPAND, (" none\n", endoff));
    549 		return;
    550 	}
    551 
    552 	if (ifsfirst.endoff > endoff) {
    553 		VTRACE(DBG_EXPAND, (" first(%d)", ifsfirst.endoff));
    554 		while (ifsfirst.next != NULL) {
    555 			struct ifsregion *ifsp;
    556 			INTOFF;
    557 			ifsp = ifsfirst.next->next;
    558 			ckfree(ifsfirst.next);
    559 			ifsfirst.next = ifsp;
    560 			INTON;
    561 		}
    562 		if (ifsfirst.begoff > endoff)
    563 			ifslastp = NULL;
    564 		else {
    565 			VTRACE(DBG_EXPAND,("->(%d,%d)",ifsfirst.begoff,endoff));
    566 			ifslastp = &ifsfirst;
    567 			ifsfirst.endoff = endoff;
    568 		}
    569 		VTRACE(DBG_EXPAND, ("\n"));
    570 		return;
    571 	}
    572 
    573 	ifslastp = &ifsfirst;
    574 	while (ifslastp->next && ifslastp->next->begoff < endoff)
    575 		ifslastp=ifslastp->next;
    576 	VTRACE(DBG_EXPAND, (" found(%d,%d)",ifslastp->begoff,ifslastp->endoff));
    577 	while (ifslastp->next != NULL) {
    578 		struct ifsregion *ifsp;
    579 		INTOFF;
    580 		ifsp = ifslastp->next->next;
    581 		ckfree(ifslastp->next);
    582 		ifslastp->next = ifsp;
    583 		INTON;
    584 	}
    585 	if (ifslastp->endoff > endoff)
    586 		ifslastp->endoff = endoff;
    587 	VTRACE(DBG_EXPAND, ("->(%d,%d)", ifslastp->begoff, ifslastp->endoff));
    588 }
    589 
    590 
    591 /*
    592  * Expand arithmetic expression.
    593  *
    594  * In this incarnation, we start at the beginning (yes, "Let's start at the
    595  * very beginning.  A very good place to start.") and collect the expression
    596  * until the end - which means expanding anything contained within.
    597  *
    598  * Fortunately, argstr() just happens to do that for us...
    599  */
    600 STATIC const char *
    601 expari(const char *p)
    602 {
    603 	char *q, *start;
    604 	intmax_t result;
    605 	int adjustment;
    606 	int begoff;
    607 	int quoted;
    608 	struct stackmark smark;
    609 
    610 	/*
    611 	 * SPACE_NEEDED is enough for all possible digits (rounded up)
    612 	 * plus possible "-", and the terminating '\0', hence, plus 2
    613 	 *
    614 	 * The calculation produces the number of bytes needed to
    615 	 * represent the biggest possible value, in octal.  We only
    616 	 * generate decimal, which takes (often) less digits (never more)
    617 	 * so this is safe, if occasionally slightly wasteful.
    618 	 */
    619 #define SPACE_NEEDED ((int)((sizeof(intmax_t) * CHAR_BIT + 2) / 3 + 2))
    620 
    621 	quoted = *p++ == '"';
    622 	begoff = expdest - stackblock();
    623 	VTRACE(DBG_EXPAND, ("expari%s: \"%s\" begoff %d\n",
    624 	    quoted ? "(quoted)" : "", p, begoff));
    625 
    626 	p = argstr(p, EXP_NL);			/* expand $(( )) string */
    627 	STPUTC('\0', expdest);
    628 	start = stackblock() + begoff;
    629 
    630 	removerecordregions(begoff);		/* nothing there is kept */
    631 	rmescapes_nl(start);		/* convert CRTNONL back into \n's */
    632 
    633 	setstackmark(&smark);
    634 	q = grabstackstr(expdest);	/* keep the expression while eval'ing */
    635 	result = arith(start, line_number);
    636 	popstackmark(&smark);		/* return the stack to before grab */
    637 
    638 	start = stackblock() + begoff;		/* block may have moved */
    639 	adjustment = expdest - start;
    640 	STADJUST(-adjustment, expdest);		/* remove the argstr() result */
    641 
    642 	CHECKSTRSPACE(SPACE_NEEDED, expdest);	/* nb: stack block might move */
    643 	fmtstr(expdest, SPACE_NEEDED, "%"PRIdMAX, result);
    644 
    645 	for (q = expdest; *q++ != '\0'; )	/* find end of what we added */
    646 		;
    647 
    648 	if (quoted == 0)			/* allow weird splitting */
    649 		recordregion(begoff, begoff + q - 1 - expdest, 0);
    650 	adjustment = q - expdest - 1;
    651 	STADJUST(adjustment, expdest);		/* move expdest to end */
    652 	VTRACE(DBG_EXPAND, ("expari: adding %d \"%s\", returning \"%.5s...\"\n",
    653 	    adjustment, stackblock() + begoff, p));
    654 
    655 	return p;
    656 }
    657 
    658 
    659 /*
    660  * Expand stuff in backwards quotes (these days, any command substitution).
    661  */
    662 
    663 STATIC void
    664 expbackq(union node *cmd, int quoted, int flag)
    665 {
    666 	struct backcmd in;
    667 	int i;
    668 	char buf[128];
    669 	char *p;
    670 	char *dest = expdest;	/* expdest may be reused by eval, use an alt */
    671 	struct ifsregion saveifs, *savelastp;
    672 	struct nodelist *saveargbackq;
    673 	char lastc;
    674 	int startloc = dest - stackblock();
    675 	const int quotes = flag & EXP_QNEEDED;
    676 	int nnl;
    677 	struct stackmark smark;
    678 
    679 	VTRACE(DBG_EXPAND, ("expbackq( ..., q=%d flag=%#x) have %d\n",
    680 	    quoted, flag, startloc));
    681 	INTOFF;
    682 	saveifs = ifsfirst;
    683 	savelastp = ifslastp;
    684 	saveargbackq = argbackq;
    685 
    686 	setstackmark(&smark);	/* preserve the stack */
    687 	p = grabstackstr(dest);	/* save what we have there currently */
    688 	evalbackcmd(cmd, &in);	/* evaluate the $( ) tree (using stack) */
    689 	popstackmark(&smark);	/* and return stack to when we entered */
    690 
    691 	ifsfirst = saveifs;
    692 	ifslastp = savelastp;
    693 	argbackq = saveargbackq;
    694 
    695 	p = in.buf;		/* now extract the results */
    696 	nnl = 0;		/* dropping trailing \n's */
    697 	for (;;) {
    698 		if (--in.nleft < 0) {
    699 			if (in.fd < 0)
    700 				break;
    701 			INTON;
    702 			while ((i = read(in.fd, buf, sizeof buf)) < 0 &&
    703 			    errno == EINTR)
    704 				continue;
    705 			INTOFF;
    706 			VTRACE(DBG_EXPAND, ("expbackq: read returns %d\n", i));
    707 			if (i <= 0)
    708 				break;
    709 			p = buf;
    710 			in.nleft = i - 1;
    711 		}
    712 		lastc = *p++;
    713 		if (lastc != '\0') {
    714 			if (lastc == '\n')	/* don't save \n yet */
    715 				nnl++;		/* it might be trailing */
    716 			else {
    717 				/*
    718 				 * We have something other than \n
    719 				 *
    720 				 * Before saving it, we need to insert
    721 				 * any \n's that we have just skipped.
    722 				 */
    723 				CHECKSTRSPACE(nnl + 2, dest);
    724 				while (nnl > 0) {
    725 					nnl--;
    726 					USTPUTC('\n', dest);
    727 				}
    728 				if ((quotes && quoted && NEEDESC(lastc)) ||
    729 				    ISCTL(lastc))
    730 					USTPUTC(CTLESC, dest);
    731 				USTPUTC(lastc, dest);
    732 			}
    733 		}
    734 	}
    735 
    736 	if (in.fd >= 0)
    737 		close(in.fd);
    738 	if (in.buf)
    739 		ckfree(in.buf);
    740 	if (in.jp)
    741 		back_exitstatus = waitforjob(in.jp);
    742 	if (quoted == 0)
    743 		recordregion(startloc, dest - stackblock(), 0);
    744 
    745 	CTRACE(DBG_EXPAND, ("evalbackq: [%d] size=%d: \"%.*s\"\n",
    746 		back_exitstatus,
    747 		(int)((dest - stackblock()) - startloc),
    748 		(int)((dest - stackblock()) - startloc),
    749 		stackblock() + startloc));
    750 
    751 	expdest = dest;		/* all done, expdest is all ours again */
    752 	INTON;
    753 }
    754 
    755 
    756 STATIC int
    757 subevalvar(const char *p, const char *str, int subtype, int startloc,
    758     int varflags)
    759 {
    760 	char *startp;
    761 	struct nodelist *saveargbackq = argbackq;
    762 	int amount;
    763 
    764 	VTRACE(DBG_EXPAND, ("subevalvar(%d) \"%.20s\" ${%.*s} sloc=%d vf=%x\n",
    765 	    subtype, p, p-str, str, startloc, varflags));
    766 	argstr(p, subtype == VSASSIGN ? EXP_VARTILDE : EXP_TILDE);
    767 	STACKSTRNUL(expdest);
    768 	argbackq = saveargbackq;
    769 	startp = stackblock() + startloc;
    770 
    771 	switch (subtype) {
    772 	case VSASSIGN:
    773 		setvar(str, startp, 0);
    774 		amount = startp - expdest;	/* remove what argstr added */
    775 		STADJUST(amount, expdest);
    776 		varflags &= ~VSNUL;	/*XXX Huh?   What's that achieve? */
    777 		return 1;			/* go back and eval var again */
    778 
    779 	case VSQUESTION:
    780 		if (*p != CTLENDVAR) {
    781 			outfmt(&errout, "%s\n", startp);
    782 			error(NULL);
    783 		}
    784 		error("%.*s: parameter %snot set",
    785 		      (int)(p - str - 1),
    786 		      str, (varflags & VSNUL) ? "null or "
    787 					      : nullstr);
    788 		/* NOTREACHED */
    789 
    790 	default:
    791 		abort();
    792 	}
    793 }
    794 
    795 STATIC int
    796 subevalvar_trim(const char *p, int strloc, int subtype, int startloc,
    797     int varflags, int quotes)
    798 {
    799 	char *startp;
    800 	char *str;
    801 	char *loc = NULL;
    802 	char *q;
    803 	int c = 0;
    804 	struct nodelist *saveargbackq = argbackq;
    805 	int amount;
    806 
    807 	switch (subtype) {
    808 	case VSTRIMLEFT:
    809 	case VSTRIMLEFTMAX:
    810 	case VSTRIMRIGHT:
    811 	case VSTRIMRIGHTMAX:
    812 		break;
    813 	default:
    814 		abort();
    815 		break;
    816 	}
    817 
    818 	VTRACE(DBG_EXPAND,
    819 	("subevalvar_trim(\"%.9s\", STR@%d, SUBT=%d, start@%d, vf=%x, q=%x)\n",
    820 		p, strloc, subtype, startloc, varflags, quotes));
    821 
    822 	argstr(p, (varflags & (VSQUOTE|VSPATQ)) == VSQUOTE ? 0 : EXP_CASE);
    823 	STACKSTRNUL(expdest);
    824 	argbackq = saveargbackq;
    825 	startp = stackblock() + startloc;
    826 	str = stackblock() + strloc;
    827 
    828 	switch (subtype) {
    829 
    830 	case VSTRIMLEFT:
    831 		for (loc = startp; loc < str; loc++) {
    832 			c = *loc;
    833 			*loc = '\0';
    834 			if (patmatch(str, startp, quotes))
    835 				goto recordleft;
    836 			*loc = c;
    837 			if (quotes && *loc == CTLESC)
    838 				loc++;
    839 		}
    840 		return 0;
    841 
    842 	case VSTRIMLEFTMAX:
    843 		for (loc = str - 1; loc >= startp;) {
    844 			c = *loc;
    845 			*loc = '\0';
    846 			if (patmatch(str, startp, quotes))
    847 				goto recordleft;
    848 			*loc = c;
    849 			loc--;
    850 			if (quotes && loc > startp &&
    851 			    *(loc - 1) == CTLESC) {
    852 				for (q = startp; q < loc; q++)
    853 					if (*q == CTLESC)
    854 						q++;
    855 				if (q > loc)
    856 					loc--;
    857 			}
    858 		}
    859 		return 0;
    860 
    861 	case VSTRIMRIGHT:
    862 		for (loc = str - 1; loc >= startp;) {
    863 			if (patmatch(str, loc, quotes))
    864 				goto recordright;
    865 			loc--;
    866 			if (quotes && loc > startp &&
    867 			    *(loc - 1) == CTLESC) {
    868 				for (q = startp; q < loc; q++)
    869 					if (*q == CTLESC)
    870 						q++;
    871 				if (q > loc)
    872 					loc--;
    873 			}
    874 		}
    875 		return 0;
    876 
    877 	case VSTRIMRIGHTMAX:
    878 		for (loc = startp; loc < str - 1; loc++) {
    879 			if (patmatch(str, loc, quotes))
    880 				goto recordright;
    881 			if (quotes && *loc == CTLESC)
    882 				loc++;
    883 		}
    884 		return 0;
    885 
    886 	default:
    887 		abort();
    888 	}
    889 
    890  recordleft:;
    891 	*loc = c;
    892 	amount = ((str - 1) - (loc - startp)) - expdest;
    893 	STADJUST(amount, expdest);
    894 	while (loc != str - 1)
    895 		*startp++ = *loc++;
    896 	return 1;
    897 
    898  recordright:;
    899 	amount = loc - expdest;
    900 	STADJUST(amount, expdest);
    901 	STPUTC('\0', expdest);
    902 	STADJUST(-1, expdest);
    903 	return 1;
    904 }
    905 
    906 
    907 /*
    908  * Expand a variable, and return a pointer to the next character in the
    909  * input string.
    910  */
    911 
    912 STATIC const char *
    913 evalvar(const char *p, int flag)
    914 {
    915 	int subtype;
    916 	int varflags;
    917 	const char *var;
    918 	char *val;
    919 	int patloc;
    920 	int c;
    921 	int set;
    922 	int special;
    923 	int startloc;
    924 	int varlen;
    925 	int apply_ifs;
    926 	const int quotes = flag & EXP_QNEEDED;
    927 
    928 	varflags = (unsigned char)*p++;
    929 	subtype = varflags & VSTYPE;
    930 	var = p;
    931 	special = subtype != VSUNKNOWN && !is_name(*p);
    932 	p = strchr(p, '=') + 1;
    933 
    934 	CTRACE(DBG_EXPAND,
    935 	    ("evalvar \"%.*s\", flag=%#x quotes=%#x vf=%#x subtype=%X\n",
    936 	    (int)(p - var - 1), var, flag, quotes, varflags, subtype));
    937 
    938  again:; /* jump here after setting a variable with ${var=text} */
    939 	if (special) {
    940 		set = varisset(var, varflags & VSNUL);
    941 		val = NULL;
    942 		if (!set && *var == '@')
    943 			empty_dollar_at = 1;
    944 	} else {
    945 		val = lookupvar(var);
    946 		if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
    947 			val = NULL;
    948 			set = 0;
    949 		} else
    950 			set = 1;
    951 	}
    952 
    953 	varlen = 0;
    954 	startloc = expdest - stackblock();
    955 
    956 	if (!set && uflag && *var != '@' && *var != '*') {
    957 		switch (subtype) {
    958 		case VSNORMAL:
    959 		case VSTRIMLEFT:
    960 		case VSTRIMLEFTMAX:
    961 		case VSTRIMRIGHT:
    962 		case VSTRIMRIGHTMAX:
    963 		case VSLENGTH:
    964 			error("%.*s: parameter not set",
    965 			    (int)(p - var - 1), var);
    966 			/* NOTREACHED */
    967 		}
    968 	}
    969 
    970 	if (set && subtype != VSPLUS) {
    971 		/* insert the value of the variable */
    972 		if (special) {
    973 			varvalue(var, varflags&VSQUOTE, subtype, flag);
    974 			if (subtype == VSLENGTH) {
    975 				varlen = expdest - stackblock() - startloc;
    976 				STADJUST(-varlen, expdest);
    977 			}
    978 		} else {
    979 
    980 			if (subtype == VSLENGTH) {
    981 				for (; *val; val++)
    982 					varlen++;
    983 			} else if (quotes && varflags & VSQUOTE) {
    984 				/*
    985 				 * If we are going to look for magic in the
    986 				 * value (quotes is set) and the expansion
    987 				 * occurs inside "" (VSQUOTE) then any char
    988 				 * that has any potential special meaning
    989 				 * needs to have that meaning suppressed,
    990 				 * so supply a CTLESC prefix for it.
    991 				 */
    992 				for (; (c = *val) != '\0'; val++) {
    993 					if (NEEDESC(c))
    994 						STPUTC(CTLESC, expdest);
    995 					STPUTC(c, expdest);
    996 				}
    997 			} else {
    998 				/*
    999 				 * We are going to rmescapes() later,
   1000 				 * so make sure that any data char that
   1001 				 * might be mistaken for one of our CTLxxx
   1002 				 * magic chars is protected ... always.
   1003 				 */
   1004 				for (; (c = *val) != '\0'; val++) {
   1005 					if (ISCTL(c))
   1006 						STPUTC(CTLESC, expdest);
   1007 					STPUTC(c, expdest);
   1008 				}
   1009 			}
   1010 		}
   1011 	}
   1012 
   1013 
   1014 	if (varflags & VSQUOTE) {
   1015 		flag |= EXP_IN_QUOTES;
   1016 		if  (*var == '@' && shellparam.nparam != 1) {
   1017 		    apply_ifs = 1;
   1018 		    VTRACE(DBG_EXPAND,
   1019 			("evalvar: VSQUOTE flag:%#x apply_ifs=1\n", flag));
   1020 		} else {
   1021 		    /*
   1022 		     * Mark so that we don't apply IFS if we recurse through
   1023 		     * here expanding $bar from "${foo-$bar}".
   1024 		     */
   1025 		    apply_ifs = 0;
   1026 		    VTRACE(DBG_EXPAND,
   1027 			("evalvar: VSQUOTE flag:%#x apply_ifs=0\n", flag));
   1028 		}
   1029 	} else if (flag & EXP_IN_QUOTES ||
   1030 		   !(flag & (EXP_SPLIT|EXP_IFS_SPLIT))) {
   1031 		apply_ifs = 0;
   1032 	} else
   1033 		apply_ifs = 1;
   1034 
   1035 	switch (subtype) {
   1036 	case VSLENGTH:
   1037 		expdest = cvtnum(varlen, expdest);
   1038 		break;
   1039 
   1040 	case VSNORMAL:
   1041 		break;
   1042 
   1043 	case VSPLUS:
   1044 		set = !set;
   1045 		/* FALLTHROUGH */
   1046 	case VSMINUS:
   1047 		if (!set) {
   1048 			VTRACE(DBG_EXPAND,
   1049 			("evalvar expanding alternate (fl=%#x apply_ifs=%d)\n",
   1050 			     flag, apply_ifs));
   1051 			argstr(p, flag |
   1052 				((flag & EXP_IN_QUOTES) ? 0 : EXP_IFS_SPLIT));
   1053 			/*
   1054 			 * ${x-a b c} doesn't get split, but removing the
   1055 			 * 'apply_ifs = 0' apparently breaks ${1+"$@"}..
   1056 			 * ${x-'a b' c} should generate 2 args.
   1057 			 */
   1058 			if (*p != CTLENDVAR || flag & EXP_IN_QUOTES)
   1059 			/* We should have marked stuff already */
   1060 				apply_ifs = 0;
   1061 		}
   1062 		break;
   1063 
   1064 	case VSTRIMLEFT:
   1065 	case VSTRIMLEFTMAX:
   1066 	case VSTRIMRIGHT:
   1067 	case VSTRIMRIGHTMAX:
   1068 		if (!set) {
   1069 			set = 1;  /* allow argbackq to be advanced if needed */
   1070 			break;
   1071 		}
   1072 		/*
   1073 		 * Terminate the string and start recording the pattern
   1074 		 * right after it
   1075 		 */
   1076 		STPUTC('\0', expdest);
   1077 		patloc = expdest - stackblock();
   1078 		if (subevalvar_trim(p, patloc, subtype, startloc, varflags,
   1079 		    quotes) == 0) {
   1080 			int amount = (expdest - stackblock() - patloc) + 1;
   1081 			STADJUST(-amount, expdest);
   1082 		}
   1083 		/* Remove any recorded regions beyond start of variable */
   1084 		removerecordregions(startloc);
   1085 		apply_ifs = 1;
   1086 		break;
   1087 
   1088 	case VSASSIGN:
   1089 	case VSQUESTION:
   1090 		if (set)
   1091 			break;
   1092 		if (subevalvar(p, var, subtype, startloc, varflags)) {
   1093 			/* if subevalvar() returns, it always returns 1 */
   1094 
   1095 			varflags &= ~VSNUL;
   1096 			/*
   1097 			 * Remove any recorded regions beyond
   1098 			 * start of variable
   1099 			 */
   1100 			removerecordregions(startloc);
   1101 			goto again;
   1102 		}
   1103 		apply_ifs = 0;		/* never executed */
   1104 		break;
   1105 
   1106 	case VSUNKNOWN:
   1107 		VTRACE(DBG_EXPAND,
   1108 	    	   ("evalvar \"%.*s\", unknown [%p %p] \"%.3s\" (%#2x %#2x)\n",
   1109 		    (int)(p-var-1), var, var, p, p, p[0]&0xFF, p[1]&0xFF));
   1110 
   1111 		if ((p - var) <= 1)
   1112 			error("%d: unknown expansion type", line_number);
   1113 		else {
   1114 			if (*p == '#')	/* only VSUNKNOWN as a ${#var:...} */
   1115 				error("%d: ${#%.*s%c..}: unknown modifier",
   1116 				     line_number, (int)(p - var - 1),
   1117 				     var, p[1]&0xFF);
   1118 
   1119 			if (*p == CTLESC)
   1120 				p++;
   1121 			error("%d: ${%.*s%c..}: unknown modifier",
   1122 			    line_number, (int)(p - var - 1), var, (*p & 0xFF));
   1123 		}
   1124 		/* NOTREACHED */
   1125 
   1126 	default:
   1127 		abort();
   1128 	}
   1129 
   1130 	if (apply_ifs)
   1131 		recordregion(startloc, expdest - stackblock(),
   1132 			     varflags & VSQUOTE);
   1133 
   1134 	if (subtype != VSNORMAL) {	/* skip to end of alternative */
   1135 		int nesting = 1;
   1136 		for (;;) {
   1137 			if ((c = *p++) == CTLESC)
   1138 				p++;
   1139 			else if (c == CTLNONL)
   1140 				;
   1141 			else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
   1142 				if (set)
   1143 					argbackq = argbackq->next;
   1144 			} else if (c == CTLVAR) {
   1145 				if ((*p++ & VSTYPE) != VSNORMAL)
   1146 					nesting++;
   1147 			} else if (c == CTLENDVAR) {
   1148 				if (--nesting == 0)
   1149 					break;
   1150 			}
   1151 		}
   1152 	}
   1153 	return p;
   1154 }
   1155 
   1156 
   1157 
   1158 /*
   1159  * Test whether a special parameter is set.
   1160  */
   1161 
   1162 STATIC int
   1163 varisset(const char *name, int notnul)
   1164 {
   1165 	if (*name == '!')
   1166 		return backgndpid != -1;
   1167 	else if (*name == '@' || *name == '*') {
   1168 		if (*shellparam.p == NULL)
   1169 			return 0;
   1170 
   1171 		if (notnul) {
   1172 			char **av;
   1173 
   1174 			for (av = shellparam.p; *av; av++)
   1175 				if (**av != '\0')
   1176 					return 1;
   1177 			return 0;
   1178 		}
   1179 	} else if (is_digit(*name)) {
   1180 		char *ap;
   1181 		long num;
   1182 
   1183 		/*
   1184 		 * handle overflow sensibly (the *ap tests should never fail)
   1185 		 */
   1186 		errno = 0;
   1187 		num = strtol(name, &ap, 10);
   1188 		if (errno != 0 || (*ap != '\0' && *ap != '='))
   1189 			return 0;
   1190 
   1191 		if (num == 0) {
   1192 			if (ap == name + 1) {	/* ${0} but not ${00} */
   1193 				ap = arg0;	/* a special param, not pos */
   1194 				if (ap == NULL)
   1195 					return 0;
   1196 			} else
   1197 				return 0;	/* ${00*} is always unset */
   1198 
   1199 		} else if (num > shellparam.nparam)
   1200 			return 0;
   1201 		else
   1202 			ap = shellparam.p[num - 1];
   1203 
   1204 		if (notnul && (ap == NULL || *ap == '\0'))
   1205 			return 0;
   1206 	}
   1207 	/*
   1208 	 * All other special params, and any positional that makes it here
   1209 	 * is set, and if requested (notnul), not ""
   1210 	 */
   1211 	return 1;
   1212 }
   1213 
   1214 
   1215 
   1216 /*
   1217  * Add the value of a specialized variable to the stack string.
   1218  */
   1219 
   1220 STATIC void
   1221 varvalue(const char *name, int quoted, int subtype, int flag)
   1222 {
   1223 	int num;
   1224 	char *p;
   1225 	int i;
   1226 	int sep;
   1227 	char **ap;
   1228 	const int start = expdest - stackblock();
   1229 
   1230 #define	START	(stackblock() + start)
   1231 #define	LENGTH	(expdest - START)
   1232 
   1233 	VTRACE(DBG_EXPAND, ("varvalue(%c%s, sub=%d, fl=%#x)", *name,
   1234 	    quoted ? ", quoted" : "", subtype, flag));
   1235 
   1236 	if (subtype == VSLENGTH)	/* no magic required ... */
   1237 		flag &= ~(EXP_FULL | EXP_QNEEDED);
   1238 
   1239 #define STRTODEST(p) \
   1240 	do {\
   1241 		if ((flag & EXP_QNEEDED) && quoted) { \
   1242 			while (*p) { \
   1243 				if (NEEDESC(*p)) \
   1244 					STPUTC(CTLESC, expdest); \
   1245 				STPUTC(*p++, expdest); \
   1246 			} \
   1247 		} else \
   1248 			while (*p) { \
   1249 				if ((flag & EXP_QNEEDED) && ISCTL(*p)) \
   1250 					STPUTC(CTLESC, expdest); \
   1251 				STPUTC(*p++, expdest); \
   1252 			} \
   1253 	} while (0)
   1254 
   1255 
   1256 	switch (*name) {
   1257 	case '$':
   1258 		num = rootpid;
   1259 		break;
   1260 	case '?':
   1261 		num = exitstatus;
   1262 		break;
   1263 	case '#':
   1264 		num = shellparam.nparam;
   1265 		break;
   1266 	case '!':
   1267 		num = backgndpid;
   1268 		break;
   1269 	case '-':
   1270 		for (i = 0; i < option_flags; i++) {
   1271 			if (optlist[optorder[i]].val)
   1272 				STPUTC(optlist[optorder[i]].letter, expdest);
   1273 		}
   1274 		VTRACE(DBG_EXPAND, (": %.*s\n", LENGTH, START));
   1275 		return;
   1276 
   1277 	case '@':
   1278 		if (flag & EXP_SPLIT && quoted) {
   1279 			VTRACE(DBG_EXPAND, (": $@ split (%d)\n",
   1280 			    shellparam.nparam));
   1281 			if (shellparam.nparam == 0)
   1282 				empty_dollar_at = 1;
   1283 
   1284 			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
   1285 				if (*p == '\0') {
   1286 					/* retain an explicit null string */
   1287 					STPUTC(CTLQUOTEMARK, expdest);
   1288 					STPUTC(CTLQUOTEEND, expdest);
   1289 				} else
   1290 					STRTODEST(p);
   1291 				if (*ap)
   1292 					/* A NUL separates args inside "" */
   1293 					STPUTC('\0', expdest);
   1294 			}
   1295 			VTRACE(DBG_EXPAND,
   1296 			    (":= \"%s\"\n", showstr(START, LENGTH)));
   1297 			return;
   1298 		}
   1299 		/* fall through */
   1300 	case '*':
   1301 		if (!quoted && (flag & EXP_SPLIT)) {
   1302 			int first = 1; int lastnull = 0;
   1303 
   1304 			for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
   1305 				if (*p == '\0') {
   1306 					lastnull = 1;
   1307 					if (first && flag & EXP_NEEDFIRST)
   1308 						STPUTC('\0', expdest);
   1309 					first = 0;
   1310 					continue;
   1311 				}
   1312 				first = lastnull = 0;
   1313 				STRTODEST(p);
   1314 				STPUTC('\0', expdest);
   1315 			}
   1316 			if (expdest > START &&
   1317 			   (!lastnull || !(flag & EXP_NEEDLAST)))
   1318 				STUNPUTC(expdest); /* delete the final \0 */
   1319 			VTRACE(DBG_EXPAND,
   1320 			    (":: \"%s\"\n", showstr(START, LENGTH)));
   1321 			return;
   1322 		}
   1323 
   1324 		/* the "$*" case, and others which act the same */
   1325 		sep = ifsval()[0];
   1326 		for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
   1327 			STRTODEST(p);
   1328 			if (!*ap)
   1329 				break;
   1330 			if (sep) {
   1331 				if (quoted && (flag & EXP_QNEEDED) &&
   1332 				    NEEDESC(sep))
   1333 					STPUTC(CTLESC, expdest);
   1334 				STPUTC(sep, expdest);
   1335 			}
   1336 		}
   1337 		VTRACE(DBG_EXPAND, (": \"%s\"\n", showstr(START, LENGTH)));
   1338 		return;
   1339 
   1340 	default:
   1341 		if (is_digit(*name)) {
   1342 			long lnum;
   1343 
   1344 			errno = 0;
   1345 			lnum = strtol(name, &p, 10);
   1346 			if (errno != 0 || (*p != '\0' && *p != '='))
   1347 				return;
   1348 
   1349 			if (lnum == 0 && p == name + 1) {
   1350 				p = arg0;
   1351 				if (p == NULL)
   1352 					return;
   1353 			} else if (lnum > 0 && lnum <= shellparam.nparam)
   1354 				p = shellparam.p[lnum - 1];
   1355 			else
   1356 				return;
   1357 			STRTODEST(p);
   1358 		}
   1359 		VTRACE(DBG_EXPAND, (": \"%s\"\n", showstr(START, LENGTH)));
   1360 		return;
   1361 	}
   1362 	/*
   1363 	 * only the specials with an int value arrive here
   1364 	 */
   1365 	VTRACE(DBG_EXPAND, ("(%d)", num));
   1366 	expdest = cvtnum(num, expdest);
   1367 	VTRACE(DBG_EXPAND, (": %.*s\n", LENGTH, START));
   1368 }
   1369 
   1370 
   1371 
   1372 /*
   1373  * Record the fact that we have to scan this region of the
   1374  * string for IFS characters.
   1375  */
   1376 
   1377 STATIC void
   1378 recordregion(int start, int end, int inquotes)
   1379 {
   1380 	struct ifsregion *ifsp;
   1381 
   1382 	inquotes = !!inquotes;
   1383 
   1384 	VTRACE(DBG_EXPAND, ("recordregion(%d,%d,%d)\n", start, end, inquotes));
   1385 	if (ifslastp == NULL) {
   1386 		ifsp = &ifsfirst;
   1387 	} else {
   1388 		if (ifslastp->endoff == start
   1389 		    && ifslastp->inquotes == inquotes) {
   1390 			/* extend previous area */
   1391 			ifslastp->endoff = end;
   1392 			return;
   1393 		}
   1394 		ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
   1395 		ifslastp->next = ifsp;
   1396 	}
   1397 	ifslastp = ifsp;
   1398 	ifslastp->next = NULL;
   1399 	ifslastp->begoff = start;
   1400 	ifslastp->endoff = end;
   1401 	ifslastp->inquotes = inquotes;
   1402 }
   1403 
   1404 
   1405 
   1406 /*
   1407  * Break the argument string into pieces based upon IFS and add the
   1408  * strings to the argument list.  The regions of the string to be
   1409  * searched for IFS characters have been stored by recordregion.
   1410  */
   1411 STATIC void
   1412 ifsbreakup(char *string, size_t len __debugused, struct arglist *arglist)
   1413 {
   1414 	struct ifsregion *ifsp;
   1415 	struct strlist *sp;
   1416 	char *start;
   1417 	char *p;
   1418 	char *q;
   1419 	const char *ifs;
   1420 	const char *ifsspc;
   1421 	int had_param_ch = 0;
   1422 
   1423 	start = string;
   1424 
   1425 	VTRACE(DBG_EXPAND, ("ifsbreakup(\"%s\")", showstr(string, (int)len)));
   1426 	if (ifslastp == NULL) {
   1427 		/* Return entire argument, IFS doesn't apply to any of it */
   1428 		VTRACE(DBG_EXPAND, ("no regions\n", string));
   1429 		sp = stalloc(sizeof(*sp));
   1430 		sp->text = start;
   1431 		*arglist->lastp = sp;
   1432 		arglist->lastp = &sp->next;
   1433 		return;
   1434 	}
   1435 
   1436 	ifs = ifsval();
   1437 
   1438 	for (ifsp = &ifsfirst; ifsp != NULL; ifsp = ifsp->next) {
   1439 		p = string + ifsp->begoff;
   1440 		VTRACE(DBG_EXPAND, ("\n%d..%d%s !%s!(%d)",
   1441 		    ifsp->begoff, ifsp->endoff,
   1442 		    ifsp->inquotes ? "Q" : "",
   1443 		    showstr(p, ifsp->endoff - ifsp->begoff),
   1444 		    ifsp->endoff - ifsp->begoff));
   1445 		while (p < string + ifsp->endoff) {
   1446 			had_param_ch = 1;
   1447 			q = p;
   1448 			if (IS_BORING(*p)) {
   1449 				p++;
   1450 				continue;
   1451 			}
   1452 			if (*p == CTLESC)
   1453 				p++;
   1454 			if (*p == '\0') {
   1455 				ifsspc = NULL;
   1456 				VTRACE(DBG_EXPAND,
   1457 				    (" \\0 Nxt:\"%s\" ",
   1458 				    showstr(p+1,ifsp->endoff-(p-string-1))));
   1459 			} else if (ifsp->inquotes) {
   1460 				p++;	/* A quoted char to keep */
   1461 				continue;
   1462 			} else {
   1463 				if (!strchr(ifs, *p)) {
   1464 					p++;	/* Not an IFS char, keep it */
   1465 					continue;
   1466 				}
   1467 				had_param_ch = 0;
   1468 				ifsspc = strchr(" \t\n", *p);
   1469 
   1470 				/* Ignore IFS whitespace at start */
   1471 				if (q == start && ifsspc != NULL) {
   1472 					p++;
   1473 					start = p;
   1474 					continue;
   1475 				}
   1476 			}
   1477 			/* Save this argument... */
   1478 			*q = '\0';
   1479 			VTRACE(DBG_EXPAND,
   1480 			    ("<%s>", showstr(start,(int)(q-start))));
   1481 			sp = stalloc(sizeof(*sp));
   1482 			sp->text = start;
   1483 			*arglist->lastp = sp;
   1484 			arglist->lastp = &sp->next;
   1485 			p++;
   1486 			if (*p == '\0') {
   1487 				if (!ifsp->inquotes &&
   1488 				    p - string + 1 < ifsp->endoff)
   1489 					/* skip embedded \0 */
   1490 					p++;
   1491 			} else if (ifsspc != NULL) {
   1492 				/* Ignore further trailing IFS whitespace */
   1493 				for (; p < string + ifsp->endoff; p++) {
   1494 					q = p;
   1495 					if (*p == CTLNONL)
   1496 						continue;
   1497 					if (*p == CTLESC)
   1498 						p++;
   1499 					if (strchr(ifs, *p) == NULL) {
   1500 						p = q;
   1501 						break;
   1502 					}
   1503 					if (*p != '\0' &&
   1504 					    strchr(" \t\n", *p) == NULL) {
   1505 						p++;
   1506 						break;
   1507 					}
   1508 				}
   1509 			}
   1510 			start = p;
   1511 		}
   1512 	}
   1513 
   1514 	/*
   1515 	 * Save anything left as an argument (as long as not empty).
   1516 	 */
   1517 	if (had_param_ch || *start != 0) {
   1518 		VTRACE(DBG_EXPAND, (" T(%zu)<%s>", strlen(start),
   1519 		    showstr(start, strlen(start))));
   1520 		sp = stalloc(sizeof(*sp));
   1521 		sp->text = start;
   1522 		*arglist->lastp = sp;
   1523 		arglist->lastp = &sp->next;
   1524 	}
   1525 	VTRACE(DBG_EXPAND, ("\n"));
   1526 }
   1527 
   1528 STATIC void
   1529 ifsfree(void)
   1530 {
   1531 	while (ifsfirst.next != NULL) {
   1532 		struct ifsregion *ifsp;
   1533 		INTOFF;
   1534 		ifsp = ifsfirst.next->next;
   1535 		ckfree(ifsfirst.next);
   1536 		ifsfirst.next = ifsp;
   1537 		INTON;
   1538 	}
   1539 	ifslastp = NULL;
   1540 	ifsfirst.next = NULL;
   1541 }
   1542 
   1543 #ifdef DEBUG
   1544 	/*
   1545 	 * DEBUG mode only utility routines so tracing can show
   1546 	 * exactly what is in strings that are being processed
   1547 	 * (including embedded \0's sometimes)
   1548 	 */
   1549 static char *
   1550 showchar(char *o, char c, int *l)
   1551 {
   1552 	if (c >= ' ' && c <= '~') {
   1553 		if (c == '\\') {
   1554 			*o++ = c;
   1555 			(*l)--;
   1556 		}
   1557 		*o++ = c;
   1558 	} else {
   1559 		if (c == 0) {
   1560 			*o++ = '\\';
   1561 			*o++ = '0';
   1562 			*l -= 1;
   1563 		} else {
   1564 			sprintf(o, "\\x%2.2X", (c & 0xFF));
   1565 			o += 4;
   1566 			*l -= 3;
   1567 		}
   1568 	}
   1569 	return o;
   1570 }
   1571 
   1572 static char *
   1573 showstr(const char *str, int len)
   1574 {
   1575 	static char strbuf[128];
   1576 	int lhs, rhs;
   1577 	const char *p;
   1578 	char *q;
   1579 
   1580 	if (len < 0)
   1581 		len = (int)strlen(str);
   1582 	if (len >= (int)sizeof strbuf - 4) {
   1583 		lhs = ((int)sizeof strbuf - 8) / 2;
   1584 		rhs = (int)sizeof strbuf - lhs - 8;
   1585 	} else {
   1586 		lhs = len;
   1587 		rhs = 0;
   1588 	}
   1589 
   1590 	for (p = str, q = strbuf; --lhs >= 0; ) {
   1591 		q = showchar(q, *p++, &rhs);
   1592 		if (q >= &strbuf[sizeof strbuf - 4]) {
   1593 			while (q < &strbuf[sizeof strbuf - 1])
   1594 				*q++ = '.';
   1595 			*q = '\0';
   1596 			return strbuf;
   1597 		}
   1598 	}
   1599 	if (p < str + len) {
   1600 		if (rhs <= 0 || q >= &strbuf[sizeof strbuf - 8]) {
   1601 			while (q < &strbuf[sizeof strbuf - 1])
   1602 				*q++ = '.';
   1603 			*q = '\0';
   1604 			return strbuf;
   1605 		}
   1606 
   1607 		*q++ = '.'; *q++ = '|'; *q++='.';
   1608 
   1609 		if (p < str + len - rhs)
   1610 			p = str + len - rhs;
   1611 		else
   1612 			rhs = str + len - p;
   1613 
   1614 		while (--rhs >= 0) {
   1615 			q = showchar(q, *p++, &lhs);
   1616 			if (q >= &strbuf[sizeof strbuf - 5]) {
   1617 				while (q < &strbuf[sizeof strbuf - 1])
   1618 					*q++ = '.';
   1619 				*q = '\0';
   1620 				return strbuf;
   1621 			}
   1622 		}
   1623 	}
   1624 	*q = '\0';
   1625 	return strbuf;
   1626 
   1627 }
   1628 #endif /* DEBUG */
   1629 
   1630 
   1631 
   1632 /*
   1633  * Expand shell metacharacters.  At this point, the only control characters
   1634  * should be escapes.  The results are stored in the list exparg.
   1635  */
   1636 
   1637 char *expdir;
   1638 
   1639 STATIC void
   1640 expandmeta(struct strlist *str, int flag)
   1641 {
   1642 	char *p;
   1643 	struct strlist **savelastp;
   1644 	struct strlist *sp;
   1645 	char c;
   1646 	/* TODO - EXP_REDIR */
   1647 
   1648 	while (str) {
   1649 		p = str->text;
   1650 		for (;;) {			/* fast check for meta chars */
   1651 			if ((c = *p++) == '\0')
   1652 				goto nometa;
   1653 			if (c == '*' || c == '?' || c == '[' /* || c == '!' */)
   1654 				break;
   1655 		}
   1656 		savelastp = exparg.lastp;
   1657 		INTOFF;
   1658 		if (expdir == NULL) {
   1659 			int i = strlen(str->text);
   1660 			expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
   1661 		}
   1662 
   1663 		expmeta(expdir, str->text);
   1664 		ckfree(expdir);
   1665 		expdir = NULL;
   1666 		INTON;
   1667 		if (exparg.lastp == savelastp) {
   1668 			/*
   1669 			 * no matches
   1670 			 */
   1671  nometa:
   1672 			*exparg.lastp = str;
   1673 			rmescapes(str->text);
   1674 			exparg.lastp = &str->next;
   1675 		} else {
   1676 			*exparg.lastp = NULL;
   1677 			*savelastp = sp = expsort(*savelastp);
   1678 			while (sp->next != NULL)
   1679 				sp = sp->next;
   1680 			exparg.lastp = &sp->next;
   1681 		}
   1682 		str = str->next;
   1683 	}
   1684 }
   1685 
   1686 STATIC void
   1687 add_args(struct strlist *str)
   1688 {
   1689 	while (str) {
   1690 		*exparg.lastp = str;
   1691 		rmescapes(str->text);
   1692 		exparg.lastp = &str->next;
   1693 		str = str->next;
   1694 	}
   1695 }
   1696 
   1697 
   1698 /*
   1699  * Do metacharacter (i.e. *, ?, [...]) expansion.
   1700  */
   1701 
   1702 STATIC void
   1703 expmeta(char *enddir, char *name)
   1704 {
   1705 	char *p;
   1706 	const char *cp;
   1707 	char *q;
   1708 	char *start;
   1709 	char *endname;
   1710 	int metaflag;
   1711 	struct stat statb;
   1712 	DIR *dirp;
   1713 	struct dirent *dp;
   1714 	int atend;
   1715 	int matchdot;
   1716 
   1717 	CTRACE(DBG_EXPAND|DBG_MATCH, ("expmeta(\"%s\")\n", name));
   1718 	metaflag = 0;
   1719 	start = name;
   1720 	for (p = name ; ; p++) {
   1721 		if (*p == '*' || *p == '?')
   1722 			metaflag = 1;
   1723 		else if (*p == '[') {
   1724 			q = p + 1;
   1725 			if (*q == '!' || *q == '^')
   1726 				q++;
   1727 			for (;;) {
   1728 				while (IS_BORING(*q))
   1729 					q++;
   1730 				if (*q == ']') {
   1731 					q++;
   1732 					metaflag = 1;
   1733 					break;
   1734 				}
   1735 				if (*q == '[' && q[1] == ':') {
   1736 					/*
   1737 					 * character class, look for :] ending
   1738 					 * also stop on ']' (end bracket expr)
   1739 					 * or '\0' or '/' (end pattern)
   1740 					 */
   1741 					while (*++q != '\0' && *q != ']' &&
   1742 					    *q != '/') {
   1743 						if (*q == CTLESC) {
   1744 							if (*++q == '\0')
   1745 								break;
   1746 							if (*q == '/')
   1747 								break;
   1748 						} else if (*q == ':' &&
   1749 						    q[1] == ']')
   1750 							break;
   1751 					}
   1752 					if (*q == ':') {
   1753 						/*
   1754 						 * stopped at ':]'
   1755 						 * still in [...]
   1756 						 * skip ":]" and continue;
   1757 						 */
   1758 						q += 2;
   1759 						continue;
   1760 					}
   1761 
   1762 					/* done at end of pattern, not [...] */
   1763 					if (*q == '\0' || *q == '/')
   1764 						break;
   1765 
   1766 					/* found the ']', we have a [...] */
   1767 					metaflag = 1;
   1768 					q++;	/* skip ']' */
   1769 					break;
   1770 				}
   1771 				if (*q == CTLESC)
   1772 					q++;
   1773 				/* end of pattern cannot be escaped */
   1774 				if (*q == '/' || *q == '\0')
   1775 					break;
   1776 				q++;
   1777 			}
   1778 		} else if (*p == '\0')
   1779 			break;
   1780 		else if (IS_BORING(*p))
   1781 			continue;
   1782 		else if (*p == CTLESC)
   1783 			p++;
   1784 		if (*p == '/') {
   1785 			if (metaflag)
   1786 				break;
   1787 			start = p + 1;
   1788 		}
   1789 	}
   1790 	if (metaflag == 0) {	/* we've reached the end of the file name */
   1791 		if (enddir != expdir)
   1792 			metaflag++;
   1793 		for (p = name ; ; p++) {
   1794 			if (IS_BORING(*p))
   1795 				continue;
   1796 			if (*p == CTLESC)
   1797 				p++;
   1798 			*enddir++ = *p;
   1799 			if (*p == '\0')
   1800 				break;
   1801 		}
   1802 		if (metaflag == 0 || lstat(expdir, &statb) >= 0)
   1803 			addfname(expdir);
   1804 		return;
   1805 	}
   1806 	endname = p;
   1807 	if (start != name) {
   1808 		p = name;
   1809 		while (p < start) {
   1810 			while (IS_BORING(*p))
   1811 				p++;
   1812 			if (*p == CTLESC)
   1813 				p++;
   1814 			*enddir++ = *p++;
   1815 		}
   1816 	}
   1817 	if (enddir == expdir) {
   1818 		cp = ".";
   1819 	} else if (enddir == expdir + 1 && *expdir == '/') {
   1820 		cp = "/";
   1821 	} else {
   1822 		cp = expdir;
   1823 		enddir[-1] = '\0';
   1824 	}
   1825 	if ((dirp = opendir(cp)) == NULL)
   1826 		return;
   1827 	if (enddir != expdir)
   1828 		enddir[-1] = '/';
   1829 	if (*endname == 0) {
   1830 		atend = 1;
   1831 	} else {
   1832 		atend = 0;
   1833 		*endname++ = '\0';
   1834 	}
   1835 	matchdot = 0;
   1836 	p = start;
   1837 	while (IS_BORING(*p))
   1838 		p++;
   1839 	if (*p == CTLESC)
   1840 		p++;
   1841 	if (*p == '.')
   1842 		matchdot++;
   1843 	while (!int_pending() && (dp = readdir(dirp)) != NULL) {
   1844 #ifndef SMALL
   1845 		if (dotglob) {
   1846 			/*
   1847 			 * When dotglob is enabled, potential matches
   1848 			 * starting with '.' are treated as any others,
   1849 			 * except for "." and ".." which require an
   1850 			 * explicit leading '.' (matchdot) in the pattern.
   1851 			 */
   1852 			if (!matchdot && dp->d_name[0] == '.' &&
   1853 			    (dp->d_name[1] == '\0' ||
   1854 			    (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
   1855 				continue;
   1856 		} else
   1857 #endif
   1858 		{
   1859 			/*
   1860 			 * When dotglob is not enabled (always not if SMALL)
   1861 			 * then files starting with a '.' only match when the
   1862 			 * pattern starts with an explicit '.' (matchdot)
   1863 			 */
   1864 			if (dp->d_name[0] == '.' && !matchdot)
   1865 				continue;
   1866 		}
   1867 
   1868 		if (patmatch(start, dp->d_name, 0)) {
   1869 			if (atend) {
   1870 				scopy(dp->d_name, enddir);
   1871 				addfname(expdir);
   1872 			} else {
   1873 				for (p = enddir, cp = dp->d_name;
   1874 				     (*p++ = *cp++) != '\0';)
   1875 					continue;
   1876 				p[-1] = '/';
   1877 				expmeta(p, endname);
   1878 			}
   1879 		}
   1880 	}
   1881 	closedir(dirp);
   1882 	if (!atend)
   1883 		endname[-1] = '/';
   1884 }
   1885 
   1886 
   1887 /*
   1888  * Add a file name to the list.
   1889  */
   1890 
   1891 STATIC void
   1892 addfname(char *name)
   1893 {
   1894 	char *p;
   1895 	struct strlist *sp;
   1896 
   1897 	p = stalloc(strlen(name) + 1);
   1898 	scopy(name, p);
   1899 	sp = stalloc(sizeof(*sp));
   1900 	sp->text = p;
   1901 	*exparg.lastp = sp;
   1902 	exparg.lastp = &sp->next;
   1903 }
   1904 
   1905 
   1906 /*
   1907  * Sort the results of file name expansion.  It calculates the number of
   1908  * strings to sort and then calls msort (short for merge sort) to do the
   1909  * work.
   1910  */
   1911 
   1912 STATIC struct strlist *
   1913 expsort(struct strlist *str)
   1914 {
   1915 	int len;
   1916 	struct strlist *sp;
   1917 
   1918 	len = 0;
   1919 	for (sp = str ; sp ; sp = sp->next)
   1920 		len++;
   1921 	return msort(str, len);
   1922 }
   1923 
   1924 
   1925 STATIC struct strlist *
   1926 msort(struct strlist *list, int len)
   1927 {
   1928 	struct strlist *p, *q = NULL;
   1929 	struct strlist **lpp;
   1930 	int half;
   1931 	int n;
   1932 
   1933 	if (len <= 1)
   1934 		return list;
   1935 	half = len >> 1;
   1936 	p = list;
   1937 	for (n = half ; --n >= 0 ; ) {
   1938 		q = p;
   1939 		p = p->next;
   1940 	}
   1941 	q->next = NULL;			/* terminate first half of list */
   1942 	q = msort(list, half);		/* sort first half of list */
   1943 	p = msort(p, len - half);		/* sort second half */
   1944 	lpp = &list;
   1945 	for (;;) {
   1946 		if (strcmp(p->text, q->text) < 0) {
   1947 			*lpp = p;
   1948 			lpp = &p->next;
   1949 			if ((p = *lpp) == NULL) {
   1950 				*lpp = q;
   1951 				break;
   1952 			}
   1953 		} else {
   1954 			*lpp = q;
   1955 			lpp = &q->next;
   1956 			if ((q = *lpp) == NULL) {
   1957 				*lpp = p;
   1958 				break;
   1959 			}
   1960 		}
   1961 	}
   1962 	return list;
   1963 }
   1964 
   1965 
   1966 /*
   1967  * See if a character matches a character class, starting at the first colon
   1968  * of "[:class:]".
   1969  * If a valid character class is recognized, a pointer to the next character
   1970  * after the final closing bracket is stored into *end, otherwise a null
   1971  * pointer is stored into *end.
   1972  */
   1973 static int
   1974 match_charclass(const char *p, wchar_t chr, const char **end)
   1975 {
   1976 	char name[20];
   1977 	const char *nameend;
   1978 	wctype_t cclass;
   1979 	char *q;
   1980 
   1981 	*end = NULL;
   1982 	p++;
   1983 	q = &name[0];
   1984 	nameend = strstr(p, ":]");
   1985 	if (nameend == NULL || nameend == p)	/* not a valid class */
   1986 		return 0;
   1987 
   1988 	if (*p == CTLESC) {
   1989 		if (*++p == CTLESC)
   1990 			return 0;
   1991 		if (p == nameend)
   1992 			return 0;
   1993 	}
   1994 	if (!is_alpha(*p))
   1995 		return 0;
   1996 	while (p < nameend) {
   1997 		if (*p == CTLESC) {
   1998 			p++;
   1999 			if (p == nameend)
   2000 				return 0;
   2001 		}
   2002 		if (!is_in_name(*p))	/* '_' is a local extension */
   2003 			return 0;
   2004 		if (q < &name[sizeof name])
   2005 			*q++ = *p++;
   2006 		else
   2007 			p++;
   2008 	}
   2009 
   2010 	*end = nameend + 2;		/* committed to it being a char class */
   2011 
   2012 	if (q < &name[sizeof name])	/* a usable name found */
   2013 		*q++ = '\0';
   2014 	else				/* too long, valid, but no match */
   2015 		return 0;
   2016 
   2017 	cclass = wctype(name);
   2018 	/* An unknown class matches nothing but is valid nevertheless. */
   2019 	if (cclass == 0)
   2020 		return 0;
   2021 	return iswctype(chr, cclass);
   2022 }
   2023 
   2024 
   2025 /*
   2026  * Returns true if the pattern matches the string.
   2027  */
   2028 
   2029 STATIC int
   2030 patmatch(const char *pattern, const char *string, int squoted)
   2031 {
   2032 	const char *p, *q, *end;
   2033 	const char *bt_p, *bt_q;
   2034 	char c;
   2035 	wchar_t wc, wc2;
   2036 
   2037 	VTRACE(DBG_MATCH, ("patmatch(P=\"%s\", W=\"%s\"%s): ",
   2038 	    pattern, string, squoted ? ", SQ" : ""));
   2039 	p = pattern;
   2040 	q = string;
   2041 	bt_p = NULL;
   2042 	bt_q = NULL;
   2043 	for (;;) {
   2044 		switch (c = *p++) {
   2045 		case '\0':
   2046 			if (squoted && *q == CTLESC) {
   2047 				if (q[1] == '\0')
   2048 					q++;
   2049 			}
   2050 			if (*q != '\0')
   2051 				goto backtrack;
   2052 			VTRACE(DBG_MATCH, ("match\n"));
   2053 			return 1;
   2054 		case CTLESC:
   2055 			if (squoted && *q == CTLESC)
   2056 				q++;
   2057 			if (*p == '\0' && *q == '\0') {
   2058 				VTRACE(DBG_MATCH, ("match-\\\n"));
   2059 				return 1;
   2060 			}
   2061 			if (*q++ != *p++)
   2062 				goto backtrack;
   2063 			break;
   2064 		case '\\':
   2065 			if (squoted && *q == CTLESC)
   2066 				q++;
   2067 			if (*q++ != *p++)
   2068 				goto backtrack;
   2069 			break;
   2070 		case CTLQUOTEMARK:
   2071 		case CTLQUOTEEND:
   2072 		case CTLNONL:
   2073 			continue;
   2074 		case '?':
   2075 			if (squoted && *q == CTLESC)
   2076 				q++;
   2077 			if (*q++ == '\0') {
   2078 				VTRACE(DBG_MATCH, ("?fail\n"));
   2079 				return 0;
   2080 			}
   2081 			break;
   2082 		case '*':
   2083 			c = *p;
   2084 			while (c == CTLQUOTEMARK || c == '*')
   2085 				c = *++p;
   2086 			if (c != CTLESC && !IS_BORING(c) &&
   2087 			    c != '?' && c != '*' && c != '[') {
   2088 				while (*q != c) {
   2089 					if (squoted && *q == CTLESC &&
   2090 					    q[1] == c)
   2091 						break;
   2092 					if (*q == '\0') {
   2093 						VTRACE(DBG_MATCH, ("*fail\n"));
   2094 						return 0;
   2095 					}
   2096 					if (squoted && *q == CTLESC)
   2097 						q++;
   2098 					q++;
   2099 				}
   2100 			}
   2101 			if (c == CTLESC && p[1] == '\0') {
   2102 				VTRACE(DBG_MATCH, ("match+\\\n"));
   2103 				return 1;
   2104 			}
   2105 			/*
   2106 			 * First try the shortest match for the '*' that
   2107 			 * could work. We can forget any earlier '*' since
   2108 			 * there is no way having it match more characters
   2109 			 * can help us, given that we are already here.
   2110 			 */
   2111 			bt_p = p;
   2112 			bt_q = q;
   2113 			break;
   2114 		case '[': {
   2115 			const char *savep, *saveq, *endp;
   2116 			int invert, found;
   2117 			unsigned char chr;
   2118 
   2119 			/*
   2120 			 * First quick check to see if there is a
   2121 			 * possible matching ']' - if not, then this
   2122 			 * is not a char class, and the '[' is just
   2123 			 * a literal '['.
   2124 			 *
   2125 			 * This check will not detect all non classes, but
   2126 			 * that's OK - It just means that we execute the
   2127 			 * harder code sometimes when it it cannot succeed.
   2128 			 */
   2129 			endp = p;
   2130 			if (*endp == '!' || *endp == '^')
   2131 				endp++;
   2132 			for (;;) {
   2133 				while (IS_BORING(*endp))
   2134 					endp++;
   2135 				if (*endp == '\0')
   2136 					goto dft;	/* no matching ] */
   2137 				if (*endp++ == ']')
   2138 					break;
   2139 			}
   2140 			/* end shortcut */
   2141 
   2142 			savep = p, saveq = q;
   2143 			invert = 0;
   2144 			if (*p == '!' || *p == '^') {
   2145 				invert++;
   2146 				p++;
   2147 			}
   2148 			found = 0;
   2149 			if (*q == '\0') {
   2150 				VTRACE(DBG_MATCH, ("[]fail\n"));
   2151 				return 0;
   2152 			}
   2153 			if (squoted && *q == CTLESC)
   2154 				q++;
   2155 			chr = (unsigned char)*q++;
   2156 			c = *p++;
   2157 			do {
   2158 				if (IS_BORING(c))
   2159 					continue;
   2160 				if (c == '\0') {
   2161 					p = savep, q = saveq;
   2162 					c = '[';
   2163 					goto dft;
   2164 				}
   2165 				if (c == '[' && *p == ':') {
   2166 					found |= match_charclass(p, chr, &end);
   2167 					if (end != NULL) {
   2168 						p = end;
   2169 						continue;
   2170 					}
   2171 				}
   2172 				if (c == CTLESC || c == '\\')
   2173 					c = *p++;
   2174 				wc = (unsigned char)c;
   2175 				if (*p == '-' && p[1] != ']') {
   2176 					p++;
   2177 					if (*p == CTLESC || *p == '\\')
   2178 						p++;
   2179 					wc2 = (unsigned char)*p++;
   2180 					if (   collate_range_cmp(chr, wc) >= 0
   2181 					    && collate_range_cmp(chr, wc2) <= 0
   2182 					   )
   2183 						found = 1;
   2184 				} else {
   2185 					if (chr == wc)
   2186 						found = 1;
   2187 				}
   2188 			} while ((c = *p++) != ']');
   2189 			if (found == invert)
   2190 				goto backtrack;
   2191 			break;
   2192 		}
   2193   dft:		default:
   2194 			if (squoted && *q == CTLESC)
   2195 				q++;
   2196 			if (*q++ == c)
   2197 				break;
   2198   backtrack:;
   2199 			/*
   2200 			 * If we have a mismatch (other than hitting the end
   2201 			 * of the string), go back to the last '*' seen and
   2202 			 * have it match one additional character.
   2203 			 */
   2204 			if (bt_p == NULL) {
   2205 				VTRACE(DBG_MATCH, ("BTP fail\n"));
   2206 				return 0;
   2207 			}
   2208 			if (*bt_q == '\0') {
   2209 				VTRACE(DBG_MATCH, ("BTQ fail\n"));
   2210 				return 0;
   2211 			}
   2212 			bt_q++;
   2213 			p = bt_p;
   2214 			q = bt_q;
   2215 			break;
   2216 		}
   2217 	}
   2218 }
   2219 
   2220 
   2221 
   2222 /*
   2223  * Remove any CTLESC or CTLNONL characters from a string.
   2224  *
   2225  * String is modified in place, and we return the length of the result
   2226  */
   2227 
   2228 int
   2229 rmescapes(char *str)
   2230 {
   2231 	char *p, *q;
   2232 
   2233 	p = str;
   2234 	while (!ISCTL(*p)) {
   2235 		if (*p++ == '\0')
   2236 			return ((int)(p - str) - 1);
   2237 	}
   2238 	q = p;
   2239 	while (*p) {
   2240 		if (IS_BORING(*p)) {
   2241 			p++;
   2242 			continue;
   2243 		}
   2244 		if (*p == CTLCNL) {
   2245 			p++;
   2246 			*q++ = '\n';
   2247 			continue;
   2248 		}
   2249 		if (*p == CTLESC)
   2250 			p++;
   2251 #ifdef DEBUG
   2252 		else if (ISCTL(*p))
   2253 			abort();
   2254 #endif
   2255 		*q++ = *p++;
   2256 	}
   2257 	*q = '\0';
   2258 
   2259 	return ((int)(q - str));
   2260 }
   2261 
   2262 /*
   2263  * and a special version for dealing with expressions to be parsed
   2264  * by the arithmetic evaluator.   That needs to be able to count \n's
   2265  * even ones that were \newline elided \n's, so we have to put the
   2266  * latter back into the string - just being careful to put them only
   2267  * at a place where white space can reasonably occur in the string
   2268  * -- then the \n we insert will just be white space, and ignored
   2269  * for all purposes except line counting.
   2270  */
   2271 
   2272 void
   2273 rmescapes_nl(char *str)
   2274 {
   2275 	char *p, *q;
   2276 	int nls = 0, holdnl = 0, holdlast;
   2277 
   2278 	p = str;
   2279 	while (!ISCTL(*p)) {
   2280 		if (*p++ == '\0')
   2281 			return;
   2282 	}
   2283 	if (p > str)	/* must reprocess char before stopper (if any) */
   2284 		--p;	/* so we do not place a \n badly */
   2285 	q = p;
   2286 	while (*p) {
   2287 		if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
   2288 			p++;
   2289 			continue;
   2290 		}
   2291 		if (*p == CTLNONL) {
   2292 			p++;
   2293 			nls++;
   2294 			continue;
   2295 		}
   2296 		if (*p == CTLCNL) {
   2297 			p++;
   2298 			*q++ = '\n';
   2299 			continue;
   2300 		}
   2301 		if (*p == CTLESC)
   2302 			p++;
   2303 #ifdef DEBUG
   2304 		else if (ISCTL(*p))
   2305 			abort();
   2306 #endif
   2307 
   2308 		holdlast = holdnl;
   2309 		holdnl = is_in_name(*p);	/* letters, digits, _ */
   2310 		if (q == str || is_space(q[-1]) || (*p != '=' && q[-1] != *p)) {
   2311 			if (nls > 0 && holdnl != holdlast) {
   2312 				while (nls > 0)
   2313 					*q++ = '\n', nls--;
   2314 			}
   2315 		}
   2316 		*q++ = *p++;
   2317 	}
   2318 	while (--nls >= 0)
   2319 		*q++ = '\n';
   2320 	*q = '\0';
   2321 }
   2322 
   2323 
   2324 
   2325 /*
   2326  * See if a pattern matches in a case statement.
   2327  */
   2328 
   2329 int
   2330 casematch(union node *pattern, char *val)
   2331 {
   2332 	struct stackmark smark;
   2333 	int result;
   2334 	char *p;
   2335 
   2336 	CTRACE(DBG_MATCH, ("casematch(P=\"%s\", W=\"%s\")\n",
   2337 	    pattern->narg.text, val));
   2338 	setstackmark(&smark);
   2339 	argbackq = pattern->narg.backquote;
   2340 	STARTSTACKSTR(expdest);
   2341 	ifslastp = NULL;
   2342 	argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
   2343 	STPUTC('\0', expdest);
   2344 	p = grabstackstr(expdest);
   2345 	result = patmatch(p, val, 0);
   2346 	popstackmark(&smark);
   2347 	return result;
   2348 }
   2349 
   2350 /*
   2351  * Our own itoa().   Assumes result buffer is on the stack
   2352  */
   2353 
   2354 STATIC char *
   2355 cvtnum(int num, char *buf)
   2356 {
   2357 	char temp[32];
   2358 	int neg = num < 0;
   2359 	char *p = temp + sizeof temp - 1;
   2360 
   2361 	if (neg)
   2362 		num = -num;
   2363 
   2364 	*p = '\0';
   2365 	do {
   2366 		*--p = num % 10 + '0';
   2367 	} while ((num /= 10) != 0 && p > temp + 1);
   2368 
   2369 	if (neg)
   2370 		*--p = '-';
   2371 
   2372 	while (*p)
   2373 		STPUTC(*p++, buf);
   2374 	return buf;
   2375 }
   2376 
   2377 /*
   2378  * Do most of the work for wordexp(3).
   2379  */
   2380 
   2381 int
   2382 wordexpcmd(int argc, char **argv)
   2383 {
   2384 	size_t len;
   2385 	int i;
   2386 
   2387 	out1fmt("%d", argc - 1);
   2388 	out1c('\0');
   2389 	for (i = 1, len = 0; i < argc; i++)
   2390 		len += strlen(argv[i]);
   2391 	out1fmt("%zu", len);
   2392 	out1c('\0');
   2393 	for (i = 1; i < argc; i++) {
   2394 		out1str(argv[i]);
   2395 		out1c('\0');
   2396 	}
   2397 	return (0);
   2398 }
   2399