Home | History | Annotate | Line # | Download | only in ksh
eval.c revision 1.6
      1 /*	$NetBSD: eval.c,v 1.6 2006/05/10 21:53:14 mrg Exp $	*/
      2 
      3 /*
      4  * Expansion - quoting, separation, substitution, globbing
      5  */
      6 #include <sys/cdefs.h>
      7 
      8 #ifndef lint
      9 __RCSID("$NetBSD: eval.c,v 1.6 2006/05/10 21:53:14 mrg Exp $");
     10 #endif
     11 
     12 
     13 #include "sh.h"
     14 #include <pwd.h>
     15 #include "ksh_dir.h"
     16 #include "ksh_stat.h"
     17 
     18 /*
     19  * string expansion
     20  *
     21  * first pass: quoting, IFS separation, ~, ${}, $() and $(()) substitution.
     22  * second pass: alternation ({,}), filename expansion (*?[]).
     23  */
     24 
     25 /* expansion generator state */
     26 typedef struct Expand {
     27 	/* int  type; */	/* see expand() */
     28 	const char *str;	/* string */
     29 	union {
     30 		const char **strv;/* string[] */
     31 		struct shf *shf;/* file */
     32 	} u;			/* source */
     33 	struct tbl *var;	/* variable in ${var..} */
     34 	short	split;		/* split "$@" / call waitlast $() */
     35 } Expand;
     36 
     37 #define	XBASE		0	/* scanning original */
     38 #define	XSUB		1	/* expanding ${} string */
     39 #define	XARGSEP		2	/* ifs0 between "$*" */
     40 #define	XARG		3	/* expanding $*, $@ */
     41 #define	XCOM		4	/* expanding $() */
     42 #define XNULLSUB	5	/* "$@" when $# is 0 (don't generate word) */
     43 
     44 /* States used for field splitting */
     45 #define IFS_WORD	0	/* word has chars (or quotes) */
     46 #define IFS_WS		1	/* have seen IFS white-space */
     47 #define IFS_NWS		2	/* have seen IFS non-white-space */
     48 
     49 static	int	varsub ARGS((Expand *xp, char *sp, char *word, int *stypep, int *slenp));
     50 static	int	comsub ARGS((Expand *xp, char *cp));
     51 static	char   *trimsub ARGS((char *str, char *pat, int how));
     52 static	void	glob ARGS((char *cp, XPtrV *wp, int markdirs));
     53 static	void	globit ARGS((XString *xs, char **xpp, char *sp, XPtrV *wp,
     54 			     int check));
     55 static char	*maybe_expand_tilde ARGS((char *p, XString *dsp, char **dpp,
     56 					  int isassign));
     57 static	char   *tilde ARGS((char *acp));
     58 static	char   *homedir ARGS((char *name));
     59 #ifdef BRACE_EXPAND
     60 static void	alt_expand ARGS((XPtrV *wp, char *start, char *exp_start,
     61 				 char *end, int fdo));
     62 #endif
     63 
     64 /* compile and expand word */
     65 char *
     66 substitute(cp, f)
     67 	const char *cp;
     68 	int f;
     69 {
     70 	struct source *s, *sold;
     71 
     72 	sold = source;
     73 	s = pushs(SWSTR, ATEMP);
     74 	s->start = s->str = cp;
     75 	source = s;
     76 	if (yylex(ONEWORD) != LWORD)
     77 		internal_errorf(1, "substitute");
     78 	source = sold;
     79 	afree(s, ATEMP);
     80 	return evalstr(yylval.cp, f);
     81 }
     82 
     83 /*
     84  * expand arg-list
     85  */
     86 char **
     87 eval(ap, f)
     88 	register char **ap;
     89 	int f;
     90 {
     91 	XPtrV w;
     92 
     93 	if (*ap == NULL)
     94 		return ap;
     95 	XPinit(w, 32);
     96 	XPput(w, NULL);		/* space for shell name */
     97 #ifdef	SHARPBANG
     98 	XPput(w, NULL);		/* and space for one arg */
     99 #endif
    100 	while (*ap != NULL)
    101 		expand(*ap++, &w, f);
    102 	XPput(w, NULL);
    103 #ifdef	SHARPBANG
    104 	return (char **) XPclose(w) + 2;
    105 #else
    106 	return (char **) XPclose(w) + 1;
    107 #endif
    108 }
    109 
    110 /*
    111  * expand string
    112  */
    113 char *
    114 evalstr(cp, f)
    115 	char *cp;
    116 	int f;
    117 {
    118 	XPtrV w;
    119 
    120 	XPinit(w, 1);
    121 	expand(cp, &w, f);
    122 	cp = (XPsize(w) == 0) ? null : (char*) *XPptrv(w);
    123 	XPfree(w);
    124 	return cp;
    125 }
    126 
    127 /*
    128  * expand string - return only one component
    129  * used from iosetup to expand redirection files
    130  */
    131 char *
    132 evalonestr(cp, f)
    133 	register char *cp;
    134 	int f;
    135 {
    136 	XPtrV w;
    137 
    138 	XPinit(w, 1);
    139 	expand(cp, &w, f);
    140 	switch (XPsize(w)) {
    141 	case 0:
    142 		cp = null;
    143 		break;
    144 	case 1:
    145 		cp = (char*) *XPptrv(w);
    146 		break;
    147 	default:
    148 		cp = evalstr(cp, f&~DOGLOB);
    149 		break;
    150 	}
    151 	XPfree(w);
    152 	return cp;
    153 }
    154 
    155 /* for nested substitution: ${var:=$var2} */
    156 typedef struct SubType {
    157 	short	stype;		/* [=+-?%#] action after expanded word */
    158 	short	base;		/* begin position of expanded word */
    159 	short	f;		/* saved value of f (DOPAT, etc) */
    160 	struct tbl *var;	/* variable for ${var..} */
    161 	short	quote;		/* saved value of quote (for ${..[%#]..}) */
    162 	struct SubType *prev;	/* old type */
    163 	struct SubType *next;	/* poped type (to avoid re-allocating) */
    164 } SubType;
    165 
    166 void
    167 expand(cp, wp, f)
    168 	char *cp;		/* input word */
    169 	register XPtrV *wp;	/* output words */
    170 	int f;			/* DO* flags */
    171 {
    172 	register int UNINITIALIZED(c);
    173 	register int type;	/* expansion type */
    174 	register int quote = 0;	/* quoted */
    175 	XString ds;		/* destination string */
    176 	register char *dp, *sp;	/* dest., source */
    177 	int fdo, word;		/* second pass flags; have word */
    178 	int doblank;		/* field splitting of parameter/command subst */
    179 	Expand x;		/* expansion variables */
    180 	SubType st_head, *st;
    181 	int UNINITIALIZED(newlines); /* For trailing newlines in COMSUB */
    182 	int saw_eq, tilde_ok;
    183 	int make_magic;
    184 	size_t len;
    185 
    186 	x.split = 0;	/* XXX gcc */
    187 	x.str = NULL;	/* XXX gcc */
    188 	if (cp == NULL)
    189 		internal_errorf(1, "expand(NULL)");
    190 	/* for alias, readonly, set, typeset commands */
    191 	if ((f & DOVACHECK) && is_wdvarassign(cp)) {
    192 		f &= ~(DOVACHECK|DOBLANK|DOGLOB|DOTILDE);
    193 		f |= DOASNTILDE;
    194 	}
    195 	if (Flag(FNOGLOB))
    196 		f &= ~DOGLOB;
    197 	if (Flag(FMARKDIRS))
    198 		f |= DOMARKDIRS;
    199 #ifdef BRACE_EXPAND
    200 	if (Flag(FBRACEEXPAND) && (f & DOGLOB))
    201 		f |= DOBRACE_;
    202 #endif /* BRACE_EXPAND */
    203 
    204 	Xinit(ds, dp, 128, ATEMP);	/* init dest. string */
    205 	type = XBASE;
    206 	sp = cp;
    207 	fdo = 0;
    208 	saw_eq = 0;
    209 	tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0; /* must be 1/0 */
    210 	doblank = 0;
    211 	make_magic = 0;
    212 	word = (f&DOBLANK) ? IFS_WS : IFS_WORD;
    213 	st_head.next = (SubType *) 0;
    214 	st = &st_head;
    215 
    216 	while (1) {
    217 		Xcheck(ds, dp);
    218 
    219 		switch (type) {
    220 		  case XBASE:	/* original prefixed string */
    221 			c = *sp++;
    222 			switch (c) {
    223 			  case EOS:
    224 				c = 0;
    225 				break;
    226 			  case CHAR:
    227 				c = *sp++;
    228 				break;
    229 			  case QCHAR:
    230 				quote |= 2; /* temporary quote */
    231 				c = *sp++;
    232 				break;
    233 			  case OQUOTE:
    234 				word = IFS_WORD;
    235 				tilde_ok = 0;
    236 				quote = 1;
    237 				continue;
    238 			  case CQUOTE:
    239 				quote = 0;
    240 				continue;
    241 			  case COMSUB:
    242 				tilde_ok = 0;
    243 				if (f & DONTRUNCOMMAND) {
    244 					word = IFS_WORD;
    245 					*dp++ = '$'; *dp++ = '(';
    246 					while (*sp != '\0') {
    247 						Xcheck(ds, dp);
    248 						*dp++ = *sp++;
    249 					}
    250 					*dp++ = ')';
    251 				} else {
    252 					type = comsub(&x, sp);
    253 					if (type == XCOM && (f&DOBLANK))
    254 						doblank++;
    255 					sp = strchr(sp, 0) + 1;
    256 					newlines = 0;
    257 				}
    258 				continue;
    259 			  case EXPRSUB:
    260 				word = IFS_WORD;
    261 				tilde_ok = 0;
    262 				if (f & DONTRUNCOMMAND) {
    263 					*dp++ = '$'; *dp++ = '('; *dp++ = '(';
    264 					while (*sp != '\0') {
    265 						Xcheck(ds, dp);
    266 						*dp++ = *sp++;
    267 					}
    268 					*dp++ = ')'; *dp++ = ')';
    269 				} else {
    270 					struct tbl v;
    271 					char *p;
    272 
    273 					v.flag = DEFINED|ISSET|INTEGER;
    274 					v.type = 10; /* not default */
    275 					v.name[0] = '\0';
    276 					v_evaluate(&v, substitute(sp, 0),
    277 						KSH_UNWIND_ERROR);
    278 					sp = strchr(sp, 0) + 1;
    279 					for (p = str_val(&v); *p; ) {
    280 						Xcheck(ds, dp);
    281 						*dp++ = *p++;
    282 					}
    283 				}
    284 				continue;
    285 			  case OSUBST: /* ${{#}var{:}[=+-?#%]word} */
    286 			  /* format is:
    287 			   *   OSUBST [{x] plain-variable-part \0
    288 			   *     compiled-word-part CSUBST [}x]
    289 			   * This is were all syntax checking gets done...
    290 			   */
    291 			  {
    292 				char *varname = ++sp; /* skip the { or x (}) */
    293 				int stype;
    294 				int slen;
    295 
    296 				slen = -1;	/* XXX gcc */
    297 				sp = strchr(sp, '\0') + 1; /* skip variable */
    298 				type = varsub(&x, varname, sp, &stype, &slen);
    299 				if (type < 0) {
    300 					char endc;
    301 					char *str, *end;
    302 
    303 					end = (char *) wdscan(sp, CSUBST);
    304 					/* ({) the } or x is already skipped */
    305 					endc = *end;
    306 					*end = EOS;
    307 					str = snptreef((char *) 0, 64, "%S",
    308 							varname - 1);
    309 					*end = endc;
    310 					errorf("%s: bad substitution", str);
    311 				}
    312 				if (f&DOBLANK)
    313 					doblank++;
    314 				tilde_ok = 0;
    315 				if (type == XBASE) {	/* expand? */
    316 					if (!st->next) {
    317 						SubType *newst;
    318 
    319 						newst = (SubType *) alloc(
    320 							sizeof(SubType), ATEMP);
    321 						newst->next = (SubType *) 0;
    322 						newst->prev = st;
    323 						st->next = newst;
    324 					}
    325 					st = st->next;
    326 					st->stype = stype;
    327 					st->base = Xsavepos(ds, dp);
    328 					st->f = f;
    329 					st->var = x.var;
    330 					st->quote = quote;
    331 					/* skip qualifier(s) */
    332 					if (stype)
    333 						sp += slen;
    334 					switch (stype & 0x7f) {
    335 					  case '#':
    336 					  case '%':
    337 						/* ! DOBLANK,DOBRACE_,DOTILDE */
    338 						f = DOPAT | (f&DONTRUNCOMMAND)
    339 						    | DOTEMP_;
    340 						quote = 0;
    341 						/* Prepend open pattern (so |
    342 						 * in a trim will work as
    343 						 * expected)
    344 						 */
    345 						*dp++ = MAGIC;
    346 						*dp++ = '@' + 0x80;
    347 						break;
    348 					  case '=':
    349 						/* Enabling tilde expansion
    350 						 * after :'s here is
    351 						 * non-standard ksh, but is
    352 						 * consistent with rules for
    353 						 * other assignments.  Not
    354 						 * sure what POSIX thinks of
    355 						 * this.
    356 						 * Not doing tilde expansion
    357 						 * for integer variables is a
    358 						 * non-POSIX thing - makes
    359 						 * sense though, since ~ is
    360 						 * a arithmetic operator.
    361 						 */
    362 						if (!(x.var->flag & INTEGER))
    363 							f |= DOASNTILDE|DOTILDE;
    364 						f |= DOTEMP_;
    365 						/* These will be done after the
    366 						 * value has been assigned.
    367 						 */
    368 						f &= ~(DOBLANK|DOGLOB|DOBRACE_);
    369 						tilde_ok = 1;
    370 						break;
    371 					  case '?':
    372 						f &= ~DOBLANK;
    373 						f |= DOTEMP_;
    374 						/* fall through */
    375 					  default:
    376 						/* Enable tilde expansion */
    377 						tilde_ok = 1;
    378 						f |= DOTILDE;
    379 					}
    380 				} else
    381 					/* skip word */
    382 					sp = (char *) wdscan(sp, CSUBST);
    383 				continue;
    384 			  }
    385 			  case CSUBST: /* only get here if expanding word */
    386 				sp++; /* ({) skip the } or x */
    387 				tilde_ok = 0;	/* in case of ${unset:-} */
    388 				*dp = '\0';
    389 				quote = st->quote;
    390 				f = st->f;
    391 				if (f&DOBLANK)
    392 					doblank--;
    393 				switch (st->stype&0x7f) {
    394 				  case '#':
    395 				  case '%':
    396 					/* Append end-pattern */
    397 					*dp++ = MAGIC; *dp++ = ')'; *dp = '\0';
    398 					dp = Xrestpos(ds, dp, st->base);
    399 					/* Must use st->var since calling
    400 					 * global would break things
    401 					 * like x[i+=1].
    402 					 */
    403 					x.str = trimsub(str_val(st->var),
    404 						dp, st->stype);
    405 					type = XSUB;
    406 					if (f&DOBLANK)
    407 						doblank++;
    408 					st = st->prev;
    409 					continue;
    410 				  case '=':
    411 					/* Restore our position and substitute
    412 					 * the value of st->var (may not be
    413 					 * the assigned value in the presence
    414 					 * of integer/right-adj/etc attributes).
    415 					 */
    416 					dp = Xrestpos(ds, dp, st->base);
    417 					/* Must use st->var since calling
    418 					 * global would cause with things
    419 					 * like x[i+=1] to be evaluated twice.
    420 					 */
    421 					/* Note: not exported by FEXPORT
    422 					 * in at&t ksh.
    423 					 */
    424 					/* XXX POSIX says readonly is only
    425 					 * fatal for special builtins (setstr
    426 					 * does readonly check).
    427 					 */
    428 					len = strlen(dp) + 1;
    429 					setstr(st->var,
    430 					    debunk((char *) alloc(len, ATEMP),
    431 						dp, len),
    432 					    KSH_UNWIND_ERROR);
    433 					x.str = str_val(st->var);
    434 					type = XSUB;
    435 					if (f&DOBLANK)
    436 						doblank++;
    437 					st = st->prev;
    438 					continue;
    439 				  case '?':
    440 				    {
    441 					char *s = Xrestpos(ds, dp, st->base);
    442 
    443 					errorf("%s: %s", st->var->name,
    444 					    dp == s ?
    445 					      "parameter null or not set"
    446 					    : (debunk(s, s, strlen(s) + 1), s));
    447 				    }
    448 				}
    449 				st = st->prev;
    450 				type = XBASE;
    451 				continue;
    452 
    453 			  case OPAT: /* open pattern: *(foo|bar) */
    454 				/* Next char is the type of pattern */
    455 				make_magic = 1;
    456 				c = *sp++ + 0x80;
    457 				break;
    458 
    459 			  case SPAT: /* pattern separator (|) */
    460 				make_magic = 1;
    461 				c = '|';
    462 				break;
    463 
    464 			  case CPAT: /* close pattern */
    465 				make_magic = 1;
    466 				c = /*(*/ ')';
    467 				break;
    468 			}
    469 			break;
    470 
    471 		  case XNULLSUB:
    472 			/* Special case for "$@" (and "${foo[@]}") - no
    473 			 * word is generated if $# is 0 (unless there is
    474 			 * other stuff inside the quotes).
    475 			 */
    476 			type = XBASE;
    477 			if (f&DOBLANK) {
    478 				doblank--;
    479 				/* not really correct: x=; "$x$@" should
    480 				 * generate a null argument and
    481 				 * set A; "${@:+}" shouldn't.
    482 				 */
    483 				if (dp == Xstring(ds, dp))
    484 					word = IFS_WS;
    485 			}
    486 			continue;
    487 
    488 		  case XSUB:
    489 			if ((c = *x.str++) == 0) {
    490 				type = XBASE;
    491 				if (f&DOBLANK)
    492 					doblank--;
    493 				continue;
    494 			}
    495 			break;
    496 
    497 		  case XARGSEP:
    498 			type = XARG;
    499 			quote = 1;
    500 		  case XARG:
    501 			if ((c = *x.str++) == '\0') {
    502 				/* force null words to be created so
    503 				 * set -- '' 2 ''; foo "$@" will do
    504 				 * the right thing
    505 				 */
    506 				if (quote && x.split)
    507 					word = IFS_WORD;
    508 				if ((x.str = *x.u.strv++) == NULL) {
    509 					type = XBASE;
    510 					if (f&DOBLANK)
    511 						doblank--;
    512 					continue;
    513 				}
    514 				c = ifs0;
    515 				if (c == 0) {
    516 					if (quote && !x.split)
    517 						continue;
    518 					c = ' ';
    519 				}
    520 				if (quote && x.split) {
    521 					/* terminate word for "$@" */
    522 					type = XARGSEP;
    523 					quote = 0;
    524 				}
    525 			}
    526 			break;
    527 
    528 		  case XCOM:
    529 			if (newlines) {		/* Spit out saved nl's */
    530 				c = '\n';
    531 				--newlines;
    532 			} else {
    533 				while ((c = shf_getc(x.u.shf)) == 0 || c == '\n')
    534 				    if (c == '\n')
    535 					    newlines++;	/* Save newlines */
    536 				if (newlines && c != EOF) {
    537 					shf_ungetc(c, x.u.shf);
    538 					c = '\n';
    539 					--newlines;
    540 				}
    541 			}
    542 			if (c == EOF) {
    543 				newlines = 0;
    544 				shf_close(x.u.shf);
    545 				if (x.split)
    546 					subst_exstat = waitlast();
    547 				type = XBASE;
    548 				if (f&DOBLANK)
    549 					doblank--;
    550 				continue;
    551 			}
    552 			break;
    553 		}
    554 
    555 		/* check for end of word or IFS separation */
    556 		if (c == 0 || (!quote && (f & DOBLANK) && doblank && !make_magic
    557 			       && ctype(c, C_IFS)))
    558 		{
    559 			/* How words are broken up:
    560 			 *		   |       value of c
    561 			 *	  word	   |	ws	nws	0
    562 			 *	-----------------------------------
    563 			 *	IFS_WORD	w/WS	w/NWS	w
    564 			 *	IFS_WS		-/WS	w/NWS	-
    565 			 *	IFS_NWS		-/NWS	w/NWS	w
    566 			 *   (w means generate a word)
    567 			 * Note that IFS_NWS/0 generates a word (at&t ksh
    568 			 * doesn't do this, but POSIX does).
    569 			 */
    570 			if (word == IFS_WORD
    571 			    || (!ctype(c, C_IFSWS) && (c || word == IFS_NWS)))
    572 			{
    573 				char *p;
    574 
    575 				*dp++ = '\0';
    576 				p = Xclose(ds, dp);
    577 #ifdef BRACE_EXPAND
    578 				if (fdo & DOBRACE_)
    579 					/* also does globbing */
    580 					alt_expand(wp, p, p,
    581 						   p + Xlength(ds, (dp - 1)),
    582 						   fdo | (f & DOMARKDIRS));
    583 				else
    584 #endif /* BRACE_EXPAND */
    585 				if (fdo & DOGLOB)
    586 					glob(p, wp, f & DOMARKDIRS);
    587 				else if ((f & DOPAT) || !(fdo & DOMAGIC_))
    588 					XPput(*wp, p);
    589 				else
    590 					XPput(*wp, debunk(p, p, strlen(p) + 1));
    591 				fdo = 0;
    592 				saw_eq = 0;
    593 				tilde_ok = (f & (DOTILDE|DOASNTILDE)) ? 1 : 0;
    594 				if (c != 0)
    595 					Xinit(ds, dp, 128, ATEMP);
    596 			}
    597 			if (c == 0)
    598 				return;
    599 			if (word != IFS_NWS)
    600 				word = ctype(c, C_IFSWS) ? IFS_WS : IFS_NWS;
    601 		} else {
    602 			/* age tilde_ok info - ~ code tests second bit */
    603 			tilde_ok <<= 1;
    604 			/* mark any special second pass chars */
    605 			if (!quote)
    606 				switch (c) {
    607 				  case '[':
    608 				  case NOT:
    609 				  case '-':
    610 				  case ']':
    611 					/* For character classes - doesn't hurt
    612 					 * to have magic !,-,]'s outside of
    613 					 * [...] expressions.
    614 					 */
    615 					if (f & (DOPAT | DOGLOB)) {
    616 						fdo |= DOMAGIC_;
    617 						if (c == '[')
    618 							fdo |= f & DOGLOB;
    619 						*dp++ = MAGIC;
    620 					}
    621 					break;
    622 				  case '*':
    623 				  case '?':
    624 					if (f & (DOPAT | DOGLOB)) {
    625 						fdo |= DOMAGIC_ | (f & DOGLOB);
    626 						*dp++ = MAGIC;
    627 					}
    628 					break;
    629 #ifdef BRACE_EXPAND
    630 				  case OBRACE:
    631 				  case ',':
    632 				  case CBRACE:
    633 					if ((f & DOBRACE_) && (c == OBRACE
    634 						|| (fdo & DOBRACE_)))
    635 					{
    636 						fdo |= DOBRACE_|DOMAGIC_;
    637 						*dp++ = MAGIC;
    638 					}
    639 					break;
    640 #endif /* BRACE_EXPAND */
    641 				  case '=':
    642 					/* Note first unquoted = for ~ */
    643 					if (!(f & DOTEMP_) && !saw_eq) {
    644 						saw_eq = 1;
    645 						tilde_ok = 1;
    646 					}
    647 					break;
    648 				  case PATHSEP: /* : */
    649 					/* Note unquoted : for ~ */
    650 					if (!(f & DOTEMP_) && (f & DOASNTILDE))
    651 						tilde_ok = 1;
    652 					break;
    653 				  case '~':
    654 					/* tilde_ok is reset whenever
    655 					 * any of ' " $( $(( ${ } are seen.
    656 					 * Note that tilde_ok must be preserved
    657 					 * through the sequence ${A=a=}~
    658 					 */
    659 					if (type == XBASE
    660 					    && (f & (DOTILDE|DOASNTILDE))
    661 					    && (tilde_ok & 2))
    662 					{
    663 						char *p, *dp_x;
    664 
    665 						dp_x = dp;
    666 						p = maybe_expand_tilde(sp,
    667 							&ds, &dp_x,
    668 							f & DOASNTILDE);
    669 						if (p) {
    670 							if (dp != dp_x)
    671 								word = IFS_WORD;
    672 							dp = dp_x;
    673 							sp = p;
    674 							continue;
    675 						}
    676 					}
    677 					break;
    678 				}
    679 			else
    680 				quote &= ~2; /* undo temporary */
    681 
    682 			if (make_magic) {
    683 				make_magic = 0;
    684 				fdo |= DOMAGIC_ | (f & DOGLOB);
    685 				*dp++ = MAGIC;
    686 			} else if (ISMAGIC(c)) {
    687 				fdo |= DOMAGIC_;
    688 				*dp++ = MAGIC;
    689 			}
    690 			*dp++ = c; /* save output char */
    691 			word = IFS_WORD;
    692 		}
    693 	}
    694 }
    695 
    696 /*
    697  * Prepare to generate the string returned by ${} substitution.
    698  */
    699 static int
    700 varsub(xp, sp, word, stypep, slenp)
    701 	Expand *xp;
    702 	char *sp;
    703 	char *word;
    704 	int *stypep;	/* becomes qualifier type */
    705 	int *slenp;	/* " " len (=, :=, etc.) valid iff *stypep != 0 */
    706 {
    707 	int c;
    708 	int state;	/* next state: XBASE, XARG, XSUB, XNULLSUB */
    709 	int stype;	/* substitution type */
    710 	int slen;
    711 	char *p;
    712 	struct tbl *vp;
    713 
    714 	if (sp[0] == '\0')	/* Bad variable name */
    715 		return -1;
    716 
    717 	xp->var = (struct tbl *) 0;
    718 
    719 	/* ${#var}, string length or array size */
    720 	if (sp[0] == '#' && (c = sp[1]) != '\0') {
    721 		int zero_ok = 0;
    722 
    723 		/* Can't have any modifiers for ${#...} */
    724 		if (*word != CSUBST)
    725 			return -1;
    726 		sp++;
    727 		/* Check for size of array */
    728 		if ((p=strchr(sp,'[')) && (p[1]=='*'||p[1]=='@') && p[2]==']') {
    729 			int n = 0;
    730 			int max = 0;
    731 			vp = global(arrayname(sp));
    732 			if (vp->flag & (ISSET|ARRAY))
    733 				zero_ok = 1;
    734 			for (; vp; vp = vp->u.array)
    735 				if (vp->flag & ISSET) {
    736 					max = vp->index + 1;
    737 					n++;
    738 				}
    739 			c = n; /* ksh88/ksh93 go for number, not max index */
    740 		} else if (c == '*' || c == '@')
    741 			c = e->loc->argc;
    742 		else {
    743 			p = str_val(global(sp));
    744 			zero_ok = p != null;
    745 			c = strlen(p);
    746 		}
    747 		if (Flag(FNOUNSET) && c == 0 && !zero_ok)
    748 			errorf("%s: parameter not set", sp);
    749 		*stypep = 0; /* unqualified variable/string substitution */
    750 		xp->str = str_save(ulton((unsigned long)c, 10), ATEMP);
    751 		return XSUB;
    752 	}
    753 
    754 	/* Check for qualifiers in word part */
    755 	stype = 0;
    756 	c = word[slen = 0] == CHAR ? word[1] : 0;
    757 	if (c == ':') {
    758 		slen += 2;
    759 		stype = 0x80;
    760 		c = word[slen + 0] == CHAR ? word[slen + 1] : 0;
    761 	}
    762 	if (ctype(c, C_SUBOP1)) {
    763 		slen += 2;
    764 		stype |= c;
    765 	} else if (ctype(c, C_SUBOP2)) { /* Note: ksh88 allows :%, :%%, etc */
    766 		slen += 2;
    767 		stype = c;
    768 		if (word[slen + 0] == CHAR && c == word[slen + 1]) {
    769 			stype |= 0x80;
    770 			slen += 2;
    771 		}
    772 	} else if (stype)	/* : is not ok */
    773 		return -1;
    774 	if (!stype && *word != CSUBST)
    775 		return -1;
    776 	*stypep = stype;
    777 	*slenp = slen;
    778 
    779 	c = sp[0];
    780 	if (c == '*' || c == '@') {
    781 		switch (stype & 0x7f) {
    782 		  case '=':	/* can't assign to a vector */
    783 		  case '%':	/* can't trim a vector (yet) */
    784 		  case '#':
    785 			return -1;
    786 		}
    787 		if (e->loc->argc == 0) {
    788 			xp->str = null;
    789 			state = c == '@' ? XNULLSUB : XSUB;
    790 		} else {
    791 			xp->u.strv = (const char **) e->loc->argv + 1;
    792 			xp->str = *xp->u.strv++;
    793 			xp->split = c == '@'; /* $@ */
    794 			state = XARG;
    795 		}
    796 	} else {
    797 		if ((p=strchr(sp,'[')) && (p[1]=='*'||p[1]=='@') && p[2]==']') {
    798 			XPtrV wv;
    799 
    800 			switch (stype & 0x7f) {
    801 			  case '=':	/* can't assign to a vector */
    802 			  case '%':	/* can't trim a vector (yet) */
    803 			  case '#':
    804 				return -1;
    805 			}
    806 			XPinit(wv, 32);
    807 			vp = global(arrayname(sp));
    808 			for (; vp; vp = vp->u.array) {
    809 				if (!(vp->flag&ISSET))
    810 					continue;
    811 				XPput(wv, str_val(vp));
    812 			}
    813 			if (XPsize(wv) == 0) {
    814 				xp->str = null;
    815 				state = p[1] == '@' ? XNULLSUB : XSUB;
    816 				XPfree(wv);
    817 			} else {
    818 				XPput(wv, 0);
    819 				xp->u.strv = (const char **) XPptrv(wv);
    820 				xp->str = *xp->u.strv++;
    821 				xp->split = p[1] == '@'; /* ${foo[@]} */
    822 				state = XARG;
    823 			}
    824 		} else {
    825 			/* Can't assign things like $! or $1 */
    826 			if ((stype & 0x7f) == '='
    827 			    && (ctype(*sp, C_VAR1) || digit(*sp)))
    828 				return -1;
    829 			xp->var = global(sp);
    830 			xp->str = str_val(xp->var);
    831 			state = XSUB;
    832 		}
    833 	}
    834 
    835 	c = stype&0x7f;
    836 	/* test the compiler's code generator */
    837 	if (ctype(c, C_SUBOP2) ||
    838 	    (((stype&0x80) ? *xp->str=='\0' : xp->str==null) ? /* undef? */
    839 	     c == '=' || c == '-' || c == '?' : c == '+'))
    840 		state = XBASE;	/* expand word instead of variable value */
    841 	if (Flag(FNOUNSET) && xp->str == null
    842 	    && (ctype(c, C_SUBOP2) || (state != XBASE && c != '+')))
    843 		errorf("%s: parameter not set", sp);
    844 	return state;
    845 }
    846 
    847 /*
    848  * Run the command in $(...) and read its output.
    849  */
    850 static int
    851 comsub(xp, cp)
    852 	register Expand *xp;
    853 	char *cp;
    854 {
    855 	Source *s, *sold;
    856 	register struct op *t;
    857 	struct shf *shf;
    858 
    859 	s = pushs(SSTRING, ATEMP);
    860 	s->start = s->str = cp;
    861 	sold = source;
    862 	t = compile(s);
    863 	source = sold;
    864 
    865 	if (t == NULL)
    866 		return XBASE;
    867 
    868 	if (t != NULL && t->type == TCOM && /* $(<file) */
    869 	    *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
    870 		register struct ioword *io = *t->ioact;
    871 		char *name;
    872 
    873 		if ((io->flag&IOTYPE) != IOREAD)
    874 			errorf("funny $() command: %s",
    875 				snptreef((char *) 0, 32, "%R", io));
    876 		shf = shf_open(name = evalstr(io->name, DOTILDE), O_RDONLY, 0,
    877 			SHF_MAPHI|SHF_CLEXEC);
    878 		if (shf == NULL)
    879 			errorf("%s: cannot open $() input", name);
    880 		xp->split = 0;	/* no waitlast() */
    881 	} else {
    882 		int ofd1, pv[2];
    883 		openpipe(pv);
    884 		shf = shf_fdopen(pv[0], SHF_RD, (struct shf *) 0);
    885 		ofd1 = savefd(1, 0);	/* fd 1 may be closed... */
    886 		if (pv[1] != 1) {
    887 			ksh_dup2(pv[1], 1, FALSE);
    888 			close(pv[1]);
    889 		}
    890 		execute(t, XFORK|XXCOM|XPIPEO);
    891 		restfd(1, ofd1);
    892 		startlast();
    893 		xp->split = 1;	/* waitlast() */
    894 	}
    895 
    896 	xp->u.shf = shf;
    897 	return XCOM;
    898 }
    899 
    900 /*
    901  * perform #pattern and %pattern substitution in ${}
    902  */
    903 
    904 static char *
    905 trimsub(str, pat, how)
    906 	register char *str;
    907 	char *pat;
    908 	int how;
    909 {
    910 	register char *end = strchr(str, 0);
    911 	register char *p, c;
    912 
    913 	switch (how&0xff) {	/* UCHAR_MAX maybe? */
    914 	  case '#':		/* shortest at beginning */
    915 		for (p = str; p <= end; p++) {
    916 			c = *p; *p = '\0';
    917 			if (gmatch(str, pat, FALSE)) {
    918 				*p = c;
    919 				return p;
    920 			}
    921 			*p = c;
    922 		}
    923 		break;
    924 	  case '#'|0x80:	/* longest match at beginning */
    925 		for (p = end; p >= str; p--) {
    926 			c = *p; *p = '\0';
    927 			if (gmatch(str, pat, FALSE)) {
    928 				*p = c;
    929 				return p;
    930 			}
    931 			*p = c;
    932 		}
    933 		break;
    934 	  case '%':		/* shortest match at end */
    935 		for (p = end; p >= str; p--) {
    936 			if (gmatch(p, pat, FALSE))
    937 				return str_nsave(str, p - str, ATEMP);
    938 		}
    939 		break;
    940 	  case '%'|0x80:	/* longest match at end */
    941 		for (p = str; p <= end; p++) {
    942 			if (gmatch(p, pat, FALSE))
    943 				return str_nsave(str, p - str, ATEMP);
    944 		}
    945 		break;
    946 	}
    947 
    948 	return str;		/* no match, return string */
    949 }
    950 
    951 /*
    952  * glob
    953  * Name derived from V6's /etc/glob, the program that expanded filenames.
    954  */
    955 
    956 /* XXX cp not const 'cause slashes are temporarily replaced with nulls... */
    957 static void
    958 glob(cp, wp, markdirs)
    959 	char *cp;
    960 	register XPtrV *wp;
    961 	int markdirs;
    962 {
    963 	int oldsize = XPsize(*wp);
    964 
    965 	if (glob_str(cp, wp, markdirs) == 0)
    966 		XPput(*wp, debunk(cp, cp, strlen(cp) + 1));
    967 	else
    968 		qsortp(XPptrv(*wp) + oldsize, (size_t)(XPsize(*wp) - oldsize),
    969 			xstrcmp);
    970 }
    971 
    972 #define GF_NONE		0
    973 #define GF_EXCHECK	BIT(0)		/* do existence check on file */
    974 #define GF_GLOBBED	BIT(1)		/* some globbing has been done */
    975 #define GF_MARKDIR	BIT(2)		/* add trailing / to directories */
    976 
    977 /* Apply file globbing to cp and store the matching files in wp.  Returns
    978  * the number of matches found.
    979  */
    980 int
    981 glob_str(cp, wp, markdirs)
    982 	char *cp;
    983 	XPtrV *wp;
    984 	int markdirs;
    985 {
    986 	int oldsize = XPsize(*wp);
    987 	XString xs;
    988 	char *xp;
    989 
    990 	Xinit(xs, xp, 256, ATEMP);
    991 	globit(&xs, &xp, cp, wp, markdirs ? GF_MARKDIR : GF_NONE);
    992 	Xfree(xs, xp);
    993 
    994 	return XPsize(*wp) - oldsize;
    995 }
    996 
    997 static void
    998 globit(xs, xpp, sp, wp, check)
    999 	XString *xs;		/* dest string */
   1000 	char **xpp;		/* ptr to dest end */
   1001 	char *sp;		/* source path */
   1002 	register XPtrV *wp;	/* output list */
   1003 	int check;		/* GF_* flags */
   1004 {
   1005 	register char *np;	/* next source component */
   1006 	char *xp = *xpp;
   1007 	char *se;
   1008 	char odirsep;
   1009 
   1010 	/* This to allow long expansions to be interrupted */
   1011 	intrcheck();
   1012 
   1013 	if (sp == NULL) {	/* end of source path */
   1014 		/* We only need to check if the file exists if a pattern
   1015 		 * is followed by a non-pattern (eg, foo*x/bar; no check
   1016 		 * is needed for foo* since the match must exist) or if
   1017 		 * any patterns were expanded and the markdirs option is set.
   1018 		 * Symlinks make things a bit tricky...
   1019 		 */
   1020 		if ((check & GF_EXCHECK)
   1021 		    || ((check & GF_MARKDIR) && (check & GF_GLOBBED)))
   1022 		{
   1023 #define stat_check()	(stat_done ? stat_done : \
   1024 			    (stat_done = stat(Xstring(*xs, xp), &statb) < 0 \
   1025 				? -1 : 1))
   1026 			struct stat lstatb, statb;
   1027 			int stat_done = 0;	 /* -1: failed, 1 ok */
   1028 
   1029 			if (lstat(Xstring(*xs, xp), &lstatb) < 0)
   1030 				return;
   1031 			/* special case for systems which strip trailing
   1032 			 * slashes from regular files (eg, /etc/passwd/).
   1033 			 * SunOS 4.1.3 does this...
   1034 			 */
   1035 			if ((check & GF_EXCHECK) && xp > Xstring(*xs, xp)
   1036 			    && ISDIRSEP(xp[-1]) && !S_ISDIR(lstatb.st_mode)
   1037 #ifdef S_ISLNK
   1038 			    && (!S_ISLNK(lstatb.st_mode)
   1039 				|| stat_check() < 0
   1040 				|| !S_ISDIR(statb.st_mode))
   1041 #endif /* S_ISLNK */
   1042 				)
   1043 				return;
   1044 			/* Possibly tack on a trailing / if there isn't already
   1045 			 * one and if the file is a directory or a symlink to a
   1046 			 * directory
   1047 			 */
   1048 			if (((check & GF_MARKDIR) && (check & GF_GLOBBED))
   1049 			    && xp > Xstring(*xs, xp) && !ISDIRSEP(xp[-1])
   1050 			    && (S_ISDIR(lstatb.st_mode)
   1051 #ifdef S_ISLNK
   1052 				|| (S_ISLNK(lstatb.st_mode)
   1053 				    && stat_check() > 0
   1054 				    && S_ISDIR(statb.st_mode))
   1055 #endif /* S_ISLNK */
   1056 				    ))
   1057 			{
   1058 				*xp++ = DIRSEP;
   1059 				*xp = '\0';
   1060 			}
   1061 		}
   1062 #ifdef OS2 /* Done this way to avoid bug in gcc 2.7.2... */
   1063     /* Ugly kludge required for command
   1064      * completion - see how search_access()
   1065      * is implemented for OS/2...
   1066      */
   1067 # define KLUDGE_VAL	4
   1068 #else /* OS2 */
   1069 # define KLUDGE_VAL	0
   1070 #endif /* OS2 */
   1071 		XPput(*wp, str_nsave(Xstring(*xs, xp), Xlength(*xs, xp)
   1072 			+ KLUDGE_VAL, ATEMP));
   1073 		return;
   1074 	}
   1075 
   1076 	if (xp > Xstring(*xs, xp))
   1077 		*xp++ = DIRSEP;
   1078 	while (ISDIRSEP(*sp)) {
   1079 		Xcheck(*xs, xp);
   1080 		*xp++ = *sp++;
   1081 	}
   1082 	np = ksh_strchr_dirsep(sp);
   1083 	if (np != NULL) {
   1084 		se = np;
   1085 		odirsep = *np;	/* don't assume DIRSEP, can be multiple kinds */
   1086 		*np++ = '\0';
   1087 	} else {
   1088 		odirsep = '\0'; /* keep gcc quiet */
   1089 		se = sp + strlen(sp);
   1090 	}
   1091 
   1092 
   1093 	/* Check if sp needs globbing - done to avoid pattern checks for strings
   1094 	 * containing MAGIC characters, open ['s without the matching close ],
   1095 	 * etc. (otherwise opendir() will be called which may fail because the
   1096 	 * directory isn't readable - if no globbing is needed, only execute
   1097 	 * permission should be required (as per POSIX)).
   1098 	 */
   1099 	if (!has_globbing(sp, se)) {
   1100 		XcheckN(*xs, xp, se - sp + 1);
   1101 		debunk(xp, sp, Xnleft(*xs, xp));
   1102 		xp += strlen(xp);
   1103 		*xpp = xp;
   1104 		globit(xs, xpp, np, wp, check);
   1105 	} else {
   1106 		DIR *dirp;
   1107 		struct dirent *d;
   1108 		char *name;
   1109 		int len;
   1110 		int prefix_len;
   1111 
   1112 		/* xp = *xpp;	   copy_non_glob() may have re-alloc'd xs */
   1113 		*xp = '\0';
   1114 		prefix_len = Xlength(*xs, xp);
   1115 		dirp = ksh_opendir(prefix_len ? Xstring(*xs, xp) : ".");
   1116 		if (dirp == NULL)
   1117 			goto Nodir;
   1118 		while ((d = readdir(dirp)) != NULL) {
   1119 			name = d->d_name;
   1120 			if (name[0] == '.' &&
   1121 			    (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
   1122 				continue; /* always ignore . and .. */
   1123 			if ((*name == '.' && *sp != '.')
   1124 			    || !gmatch(name, sp, TRUE))
   1125 				continue;
   1126 
   1127 			len = NLENGTH(d) + 1;
   1128 			XcheckN(*xs, xp, len);
   1129 			memcpy(xp, name, len);
   1130 			*xpp = xp + len - 1;
   1131 			globit(xs, xpp, np, wp,
   1132 				(check & GF_MARKDIR) | GF_GLOBBED
   1133 				| (np ? GF_EXCHECK : GF_NONE));
   1134 			xp = Xstring(*xs, xp) + prefix_len;
   1135 		}
   1136 		closedir(dirp);
   1137 	  Nodir:;
   1138 	}
   1139 
   1140 	if (np != NULL)
   1141 		*--np = odirsep;
   1142 }
   1143 
   1144 #if 0
   1145 /* Check if p contains something that needs globbing; if it does, 0 is
   1146  * returned; if not, p is copied into xs/xp after stripping any MAGICs
   1147  */
   1148 static int	copy_non_glob ARGS((XString *xs, char **xpp, char *p));
   1149 static int
   1150 copy_non_glob(xs, xpp, p)
   1151 	XString *xs;
   1152 	char **xpp;
   1153 	char *p;
   1154 {
   1155 	char *xp;
   1156 	int len = strlen(p);
   1157 
   1158 	XcheckN(*xs, *xpp, len);
   1159 	xp = *xpp;
   1160 	for (; *p; p++) {
   1161 		if (ISMAGIC(*p)) {
   1162 			int c = *++p;
   1163 
   1164 			if (c == '*' || c == '?')
   1165 				return 0;
   1166 			if (*p == '[') {
   1167 				char *q = p + 1;
   1168 
   1169 				if (ISMAGIC(*q) && q[1] == NOT)
   1170 					q += 2;
   1171 				if (ISMAGIC(*q) && q[1] == ']')
   1172 					q += 2;
   1173 				for (; *q; q++)
   1174 					if (ISMAGIC(*q) && *++q == ']')
   1175 						return 0;
   1176 				/* pass a literal [ through */
   1177 			}
   1178 			/* must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, etc. */
   1179 		}
   1180 		*xp++ = *p;
   1181 	}
   1182 	*xp = '\0';
   1183 	*xpp = xp;
   1184 	return 1;
   1185 }
   1186 #endif /* 0 */
   1187 
   1188 /* remove MAGIC from string */
   1189 char *
   1190 debunk(dp, sp, dlen)
   1191 	char *dp;
   1192 	const char *sp;
   1193 	size_t dlen;
   1194 {
   1195 	char *d, *s;
   1196 
   1197 	if ((s = strchr(sp, MAGIC))) {
   1198 		if (s - sp >= dlen)
   1199 			return dp;
   1200 		memcpy(dp, sp, s - sp);
   1201 		for (d = dp + (s - sp); *s && (d - dp < dlen); s++)
   1202 			if (!ISMAGIC(*s) || !(*++s & 0x80)
   1203 			    || !strchr("*+?@! ", *s & 0x7f))
   1204 				*d++ = *s;
   1205 			else {
   1206 				/* extended pattern operators: *+?@! */
   1207 				if ((*s & 0x7f) != ' ')
   1208 					*d++ = *s & 0x7f;
   1209 				if (d - dp < dlen)
   1210 					*d++ = '(';
   1211 			}
   1212 		*d = '\0';
   1213 	} else if (dp != sp)
   1214 		strlcpy(dp, sp, dlen);
   1215 	return dp;
   1216 }
   1217 
   1218 /* Check if p is an unquoted name, possibly followed by a / or :.  If so
   1219  * puts the expanded version in *dcp,dp and returns a pointer in p just
   1220  * past the name, otherwise returns 0.
   1221  */
   1222 static char *
   1223 maybe_expand_tilde(p, dsp, dpp, isassign)
   1224 	char *p;
   1225 	XString *dsp;
   1226 	char **dpp;
   1227 	int isassign;
   1228 {
   1229 	XString ts;
   1230 	char *dp = *dpp;
   1231 	char *tp, *r;
   1232 
   1233 	Xinit(ts, tp, 16, ATEMP);
   1234 	/* : only for DOASNTILDE form */
   1235 	while (p[0] == CHAR && !ISDIRSEP(p[1])
   1236 	       && (!isassign || p[1] != PATHSEP))
   1237 	{
   1238 		Xcheck(ts, tp);
   1239 		*tp++ = p[1];
   1240 		p += 2;
   1241 	}
   1242 	*tp = '\0';
   1243 	r = (p[0] == EOS || p[0] == CHAR || p[0] == CSUBST) ? tilde(Xstring(ts, tp)) : (char *) 0;
   1244 	Xfree(ts, tp);
   1245 	if (r) {
   1246 		while (*r) {
   1247 			Xcheck(*dsp, dp);
   1248 			if (ISMAGIC(*r))
   1249 				*dp++ = MAGIC;
   1250 			*dp++ = *r++;
   1251 		}
   1252 		*dpp = dp;
   1253 		r = p;
   1254 	}
   1255 	return r;
   1256 }
   1257 
   1258 /*
   1259  * tilde expansion
   1260  *
   1261  * based on a version by Arnold Robbins
   1262  */
   1263 
   1264 static char *
   1265 tilde(cp)
   1266 	char *cp;
   1267 {
   1268 	char *dp;
   1269 
   1270 	if (cp[0] == '\0')
   1271 		dp = str_val(global("HOME"));
   1272 	else if (cp[0] == '+' && cp[1] == '\0')
   1273 		dp = str_val(global("PWD"));
   1274 	else if (cp[0] == '-' && cp[1] == '\0')
   1275 		dp = str_val(global("OLDPWD"));
   1276 	else
   1277 		dp = homedir(cp);
   1278 	/* If HOME, PWD or OLDPWD are not set, don't expand ~ */
   1279 	if (dp == null)
   1280 		dp = (char *) 0;
   1281 	return dp;
   1282 }
   1283 
   1284 /*
   1285  * map userid to user's home directory.
   1286  * note that 4.3's getpw adds more than 6K to the shell,
   1287  * and the YP version probably adds much more.
   1288  * we might consider our own version of getpwnam() to keep the size down.
   1289  */
   1290 
   1291 static char *
   1292 homedir(name)
   1293 	char *name;
   1294 {
   1295 	register struct tbl *ap;
   1296 
   1297 	ap = tenter(&homedirs, name, hash(name));
   1298 	if (!(ap->flag & ISSET)) {
   1299 #ifdef OS2
   1300 		/* No usernames in OS2 - punt */
   1301 		return NULL;
   1302 #else /* OS2 */
   1303 		struct passwd *pw;
   1304 
   1305 		pw = getpwnam(name);
   1306 		if (pw == NULL)
   1307 			return NULL;
   1308 		ap->val.s = str_save(pw->pw_dir, APERM);
   1309 		ap->flag |= DEFINED|ISSET|ALLOC;
   1310 #endif /* OS2 */
   1311 	}
   1312 	return ap->val.s;
   1313 }
   1314 
   1315 #ifdef BRACE_EXPAND
   1316 static void
   1317 alt_expand(wp, start, exp_start, end, fdo)
   1318 	XPtrV *wp;
   1319 	char *start, *exp_start;
   1320 	char *end;
   1321 	int fdo;
   1322 {
   1323 	int UNINITIALIZED(count);
   1324 	char *brace_start, *brace_end, *UNINITIALIZED(comma);
   1325 	char *field_start;
   1326 	char *p;
   1327 
   1328 	/* search for open brace */
   1329 	for (p = exp_start; (p = strchr(p, MAGIC)) && p[1] != OBRACE; p += 2)
   1330 		;
   1331 	brace_start = p;
   1332 
   1333 	/* find matching close brace, if any */
   1334 	if (p) {
   1335 		comma = (char *) 0;
   1336 		count = 1;
   1337 		for (p += 2; *p && count; p++) {
   1338 			if (ISMAGIC(*p)) {
   1339 				if (*++p == OBRACE)
   1340 					count++;
   1341 				else if (*p == CBRACE)
   1342 					--count;
   1343 				else if (*p == ',' && count == 1)
   1344 					comma = p;
   1345 			}
   1346 		}
   1347 	}
   1348 	/* no valid expansions... */
   1349 	if (!p || count != 0) {
   1350 		/* Note that given a{{b,c} we do not expand anything (this is
   1351 		 * what at&t ksh does.  This may be changed to do the {b,c}
   1352 		 * expansion. }
   1353 		 */
   1354 		if (fdo & DOGLOB)
   1355 			glob(start, wp, fdo & DOMARKDIRS);
   1356 		else
   1357 			XPput(*wp, debunk(start, start, end - start));
   1358 		return;
   1359 	}
   1360 	brace_end = p;
   1361 	if (!comma) {
   1362 		alt_expand(wp, start, brace_end, end, fdo);
   1363 		return;
   1364 	}
   1365 
   1366 	/* expand expression */
   1367 	field_start = brace_start + 2;
   1368 	count = 1;
   1369 	for (p = brace_start + 2; p != brace_end; p++) {
   1370 		if (ISMAGIC(*p)) {
   1371 			if (*++p == OBRACE)
   1372 				count++;
   1373 			else if ((*p == CBRACE && --count == 0)
   1374 				 || (*p == ',' && count == 1))
   1375 			{
   1376 				char *new;
   1377 				int l1, l2, l3;
   1378 
   1379 				l1 = brace_start - start;
   1380 				l2 = (p - 1) - field_start;
   1381 				l3 = end - brace_end;
   1382 				new = (char *) alloc(l1 + l2 + l3 + 1, ATEMP);
   1383 				memcpy(new, start, l1);
   1384 				memcpy(new + l1, field_start, l2);
   1385 				memcpy(new + l1 + l2, brace_end, l3);
   1386 				new[l1 + l2 + l3] = '\0';
   1387 				alt_expand(wp, new, new + l1,
   1388 					   new + l1 + l2 + l3, fdo);
   1389 				field_start = p + 1;
   1390 			}
   1391 		}
   1392 	}
   1393 	return;
   1394 }
   1395 #endif /* BRACE_EXPAND */
   1396