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