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