xref: /freebsd/bin/sh/parser.c (revision b9f654b163bce26de79705e77b872427c9f2afa1)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 #if 0
37 static char sccsid[] = "@(#)parser.c	8.7 (Berkeley) 5/16/95";
38 #endif
39 #endif /* not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include <sys/param.h>
44 #include <pwd.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <stdio.h>
48 
49 #include "shell.h"
50 #include "parser.h"
51 #include "nodes.h"
52 #include "expand.h"	/* defines rmescapes() */
53 #include "syntax.h"
54 #include "options.h"
55 #include "input.h"
56 #include "output.h"
57 #include "var.h"
58 #include "error.h"
59 #include "memalloc.h"
60 #include "mystring.h"
61 #include "alias.h"
62 #include "show.h"
63 #include "eval.h"
64 #include "exec.h"	/* to check for special builtins */
65 #ifndef NO_HISTORY
66 #include "myhistedit.h"
67 #endif
68 
69 /*
70  * Shell command parser.
71  */
72 
73 #define	PROMPTLEN	128
74 
75 /* values of checkkwd variable */
76 #define CHKALIAS	0x1
77 #define CHKKWD		0x2
78 #define CHKNL		0x4
79 
80 /* values returned by readtoken */
81 #include "token.h"
82 
83 
84 
85 struct heredoc {
86 	struct heredoc *next;	/* next here document in list */
87 	union node *here;		/* redirection node */
88 	char *eofmark;		/* string indicating end of input */
89 	int striptabs;		/* if set, strip leading tabs */
90 };
91 
92 struct parser_temp {
93 	struct parser_temp *next;
94 	void *data;
95 };
96 
97 
98 static struct heredoc *heredoclist;	/* list of here documents to read */
99 static int doprompt;		/* if set, prompt the user */
100 static int needprompt;		/* true if interactive and at start of line */
101 static int lasttoken;		/* last token read */
102 static int tokpushback;		/* last token pushed back */
103 static char *wordtext;		/* text of last word returned by readtoken */
104 static int checkkwd;
105 static struct nodelist *backquotelist;
106 static union node *redirnode;
107 static struct heredoc *heredoc;
108 static int quoteflag;		/* set if (part of) last token was quoted */
109 static int startlinno;		/* line # where last token started */
110 static int funclinno;		/* line # where the current function started */
111 static struct parser_temp *parser_temp;
112 
113 #define NOEOFMARK ((const char *)&heredoclist)
114 
115 
116 static union node *list(int);
117 static union node *andor(void);
118 static union node *pipeline(void);
119 static union node *command(void);
120 static union node *simplecmd(union node **, union node *);
121 static union node *makename(void);
122 static union node *makebinary(int type, union node *n1, union node *n2);
123 static void parsefname(void);
124 static void parseheredoc(void);
125 static int peektoken(void);
126 static int readtoken(void);
127 static int xxreadtoken(void);
128 static int readtoken1(int, const char *, const char *, int);
129 static int noexpand(char *);
130 static void consumetoken(int);
131 static void synexpect(int) __dead2;
132 static void synerror(const char *) __dead2;
133 static void setprompt(int);
134 static int pgetc_linecont(void);
135 static void getusername(char *, size_t);
136 
137 
138 static void *
139 parser_temp_alloc(size_t len)
140 {
141 	struct parser_temp *t;
142 
143 	INTOFF;
144 	t = ckmalloc(sizeof(*t));
145 	t->data = NULL;
146 	t->next = parser_temp;
147 	parser_temp = t;
148 	t->data = ckmalloc(len);
149 	INTON;
150 	return t->data;
151 }
152 
153 
154 static void *
155 parser_temp_realloc(void *ptr, size_t len)
156 {
157 	struct parser_temp *t;
158 
159 	INTOFF;
160 	t = parser_temp;
161 	if (ptr != t->data)
162 		error("bug: parser_temp_realloc misused");
163 	t->data = ckrealloc(t->data, len);
164 	INTON;
165 	return t->data;
166 }
167 
168 
169 static void
170 parser_temp_free_upto(void *ptr)
171 {
172 	struct parser_temp *t;
173 	int done = 0;
174 
175 	INTOFF;
176 	while (parser_temp != NULL && !done) {
177 		t = parser_temp;
178 		parser_temp = t->next;
179 		done = t->data == ptr;
180 		ckfree(t->data);
181 		ckfree(t);
182 	}
183 	INTON;
184 	if (!done)
185 		error("bug: parser_temp_free_upto misused");
186 }
187 
188 
189 static void
190 parser_temp_free_all(void)
191 {
192 	struct parser_temp *t;
193 
194 	INTOFF;
195 	while (parser_temp != NULL) {
196 		t = parser_temp;
197 		parser_temp = t->next;
198 		ckfree(t->data);
199 		ckfree(t);
200 	}
201 	INTON;
202 }
203 
204 
205 /*
206  * Read and parse a command.  Returns NEOF on end of file.  (NULL is a
207  * valid parse tree indicating a blank line.)
208  */
209 
210 union node *
211 parsecmd(int interact)
212 {
213 	int t;
214 
215 	/* This assumes the parser is not re-entered,
216 	 * which could happen if we add command substitution on PS1/PS2.
217 	 */
218 	parser_temp_free_all();
219 	heredoclist = NULL;
220 
221 	tokpushback = 0;
222 	checkkwd = 0;
223 	doprompt = interact;
224 	if (doprompt)
225 		setprompt(1);
226 	else
227 		setprompt(0);
228 	needprompt = 0;
229 	t = readtoken();
230 	if (t == TEOF)
231 		return NEOF;
232 	if (t == TNL)
233 		return NULL;
234 	tokpushback++;
235 	return list(1);
236 }
237 
238 
239 /*
240  * Read and parse words for wordexp.
241  * Returns a list of NARG nodes; NULL if there are no words.
242  */
243 union node *
244 parsewordexp(void)
245 {
246 	union node *n, *first = NULL, **pnext;
247 	int t;
248 
249 	/* This assumes the parser is not re-entered,
250 	 * which could happen if we add command substitution on PS1/PS2.
251 	 */
252 	parser_temp_free_all();
253 	heredoclist = NULL;
254 
255 	tokpushback = 0;
256 	checkkwd = 0;
257 	doprompt = 0;
258 	setprompt(0);
259 	needprompt = 0;
260 	pnext = &first;
261 	while ((t = readtoken()) != TEOF) {
262 		if (t != TWORD)
263 			synexpect(TWORD);
264 		n = makename();
265 		*pnext = n;
266 		pnext = &n->narg.next;
267 	}
268 	return first;
269 }
270 
271 
272 static union node *
273 list(int nlflag)
274 {
275 	union node *ntop, *n1, *n2, *n3;
276 	int tok;
277 
278 	checkkwd = CHKNL | CHKKWD | CHKALIAS;
279 	if (!nlflag && tokendlist[peektoken()])
280 		return NULL;
281 	ntop = n1 = NULL;
282 	for (;;) {
283 		n2 = andor();
284 		tok = readtoken();
285 		if (tok == TBACKGND) {
286 			if (n2 != NULL && n2->type == NPIPE) {
287 				n2->npipe.backgnd = 1;
288 			} else if (n2 != NULL && n2->type == NREDIR) {
289 				n2->type = NBACKGND;
290 			} else {
291 				n3 = (union node *)stalloc(sizeof (struct nredir));
292 				n3->type = NBACKGND;
293 				n3->nredir.n = n2;
294 				n3->nredir.redirect = NULL;
295 				n2 = n3;
296 			}
297 		}
298 		if (ntop == NULL)
299 			ntop = n2;
300 		else if (n1 == NULL) {
301 			n1 = makebinary(NSEMI, ntop, n2);
302 			ntop = n1;
303 		}
304 		else {
305 			n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
306 			n1->nbinary.ch2 = n3;
307 			n1 = n3;
308 		}
309 		switch (tok) {
310 		case TBACKGND:
311 		case TSEMI:
312 			tok = readtoken();
313 			/* FALLTHROUGH */
314 		case TNL:
315 			if (tok == TNL) {
316 				parseheredoc();
317 				if (nlflag)
318 					return ntop;
319 			} else if (tok == TEOF && nlflag) {
320 				parseheredoc();
321 				return ntop;
322 			} else {
323 				tokpushback++;
324 			}
325 			checkkwd = CHKNL | CHKKWD | CHKALIAS;
326 			if (!nlflag && tokendlist[peektoken()])
327 				return ntop;
328 			break;
329 		case TEOF:
330 			if (heredoclist)
331 				parseheredoc();
332 			else
333 				pungetc();		/* push back EOF on input */
334 			return ntop;
335 		default:
336 			if (nlflag)
337 				synexpect(-1);
338 			tokpushback++;
339 			return ntop;
340 		}
341 	}
342 }
343 
344 
345 
346 static union node *
347 andor(void)
348 {
349 	union node *n;
350 	int t;
351 
352 	n = pipeline();
353 	for (;;) {
354 		if ((t = readtoken()) == TAND) {
355 			t = NAND;
356 		} else if (t == TOR) {
357 			t = NOR;
358 		} else {
359 			tokpushback++;
360 			return n;
361 		}
362 		n = makebinary(t, n, pipeline());
363 	}
364 }
365 
366 
367 
368 static union node *
369 pipeline(void)
370 {
371 	union node *n1, *n2, *pipenode;
372 	struct nodelist *lp, *prev;
373 	int negate, t;
374 
375 	negate = 0;
376 	checkkwd = CHKNL | CHKKWD | CHKALIAS;
377 	TRACE(("pipeline: entered\n"));
378 	while (readtoken() == TNOT)
379 		negate = !negate;
380 	tokpushback++;
381 	n1 = command();
382 	if (readtoken() == TPIPE) {
383 		pipenode = (union node *)stalloc(sizeof (struct npipe));
384 		pipenode->type = NPIPE;
385 		pipenode->npipe.backgnd = 0;
386 		lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
387 		pipenode->npipe.cmdlist = lp;
388 		lp->n = n1;
389 		do {
390 			prev = lp;
391 			lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
392 			checkkwd = CHKNL | CHKKWD | CHKALIAS;
393 			t = readtoken();
394 			tokpushback++;
395 			if (t == TNOT)
396 				lp->n = pipeline();
397 			else
398 				lp->n = command();
399 			prev->next = lp;
400 		} while (readtoken() == TPIPE);
401 		lp->next = NULL;
402 		n1 = pipenode;
403 	}
404 	tokpushback++;
405 	if (negate) {
406 		n2 = (union node *)stalloc(sizeof (struct nnot));
407 		n2->type = NNOT;
408 		n2->nnot.com = n1;
409 		return n2;
410 	} else
411 		return n1;
412 }
413 
414 
415 
416 static union node *
417 command(void)
418 {
419 	union node *n1, *n2;
420 	union node *ap, **app;
421 	union node *cp, **cpp;
422 	union node *redir, **rpp;
423 	int t;
424 	int is_subshell;
425 
426 	checkkwd = CHKNL | CHKKWD | CHKALIAS;
427 	is_subshell = 0;
428 	redir = NULL;
429 	n1 = NULL;
430 	rpp = &redir;
431 
432 	/* Check for redirection which may precede command */
433 	while (readtoken() == TREDIR) {
434 		*rpp = n2 = redirnode;
435 		rpp = &n2->nfile.next;
436 		parsefname();
437 	}
438 	tokpushback++;
439 
440 	switch (readtoken()) {
441 	case TIF:
442 		n1 = (union node *)stalloc(sizeof (struct nif));
443 		n1->type = NIF;
444 		if ((n1->nif.test = list(0)) == NULL)
445 			synexpect(-1);
446 		consumetoken(TTHEN);
447 		n1->nif.ifpart = list(0);
448 		n2 = n1;
449 		while (readtoken() == TELIF) {
450 			n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
451 			n2 = n2->nif.elsepart;
452 			n2->type = NIF;
453 			if ((n2->nif.test = list(0)) == NULL)
454 				synexpect(-1);
455 			consumetoken(TTHEN);
456 			n2->nif.ifpart = list(0);
457 		}
458 		if (lasttoken == TELSE)
459 			n2->nif.elsepart = list(0);
460 		else {
461 			n2->nif.elsepart = NULL;
462 			tokpushback++;
463 		}
464 		consumetoken(TFI);
465 		checkkwd = CHKKWD | CHKALIAS;
466 		break;
467 	case TWHILE:
468 	case TUNTIL:
469 		t = lasttoken;
470 		if ((n1 = list(0)) == NULL)
471 			synexpect(-1);
472 		consumetoken(TDO);
473 		n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
474 		consumetoken(TDONE);
475 		checkkwd = CHKKWD | CHKALIAS;
476 		break;
477 	case TFOR:
478 		if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
479 			synerror("Bad for loop variable");
480 		n1 = (union node *)stalloc(sizeof (struct nfor));
481 		n1->type = NFOR;
482 		n1->nfor.var = wordtext;
483 		while (readtoken() == TNL)
484 			;
485 		if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) {
486 			app = &ap;
487 			while (readtoken() == TWORD) {
488 				n2 = makename();
489 				*app = n2;
490 				app = &n2->narg.next;
491 			}
492 			*app = NULL;
493 			n1->nfor.args = ap;
494 			if (lasttoken != TNL && lasttoken != TSEMI)
495 				synexpect(-1);
496 		} else {
497 			static char argvars[5] = {
498 				CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
499 			};
500 			n2 = (union node *)stalloc(sizeof (struct narg));
501 			n2->type = NARG;
502 			n2->narg.text = argvars;
503 			n2->narg.backquote = NULL;
504 			n2->narg.next = NULL;
505 			n1->nfor.args = n2;
506 			/*
507 			 * Newline or semicolon here is optional (but note
508 			 * that the original Bourne shell only allowed NL).
509 			 */
510 			if (lasttoken != TNL && lasttoken != TSEMI)
511 				tokpushback++;
512 		}
513 		checkkwd = CHKNL | CHKKWD | CHKALIAS;
514 		if ((t = readtoken()) == TDO)
515 			t = TDONE;
516 		else if (t == TBEGIN)
517 			t = TEND;
518 		else
519 			synexpect(-1);
520 		n1->nfor.body = list(0);
521 		consumetoken(t);
522 		checkkwd = CHKKWD | CHKALIAS;
523 		break;
524 	case TCASE:
525 		n1 = (union node *)stalloc(sizeof (struct ncase));
526 		n1->type = NCASE;
527 		consumetoken(TWORD);
528 		n1->ncase.expr = makename();
529 		while (readtoken() == TNL);
530 		if (lasttoken != TWORD || ! equal(wordtext, "in"))
531 			synerror("expecting \"in\"");
532 		cpp = &n1->ncase.cases;
533 		checkkwd = CHKNL | CHKKWD, readtoken();
534 		while (lasttoken != TESAC) {
535 			*cpp = cp = (union node *)stalloc(sizeof (struct nclist));
536 			cp->type = NCLIST;
537 			app = &cp->nclist.pattern;
538 			if (lasttoken == TLP)
539 				readtoken();
540 			for (;;) {
541 				*app = ap = makename();
542 				checkkwd = CHKNL | CHKKWD;
543 				if (readtoken() != TPIPE)
544 					break;
545 				app = &ap->narg.next;
546 				readtoken();
547 			}
548 			ap->narg.next = NULL;
549 			if (lasttoken != TRP)
550 				synexpect(TRP);
551 			cp->nclist.body = list(0);
552 
553 			checkkwd = CHKNL | CHKKWD | CHKALIAS;
554 			if ((t = readtoken()) != TESAC) {
555 				if (t == TENDCASE)
556 					;
557 				else if (t == TFALLTHRU)
558 					cp->type = NCLISTFALLTHRU;
559 				else
560 					synexpect(TENDCASE);
561 				checkkwd = CHKNL | CHKKWD, readtoken();
562 			}
563 			cpp = &cp->nclist.next;
564 		}
565 		*cpp = NULL;
566 		checkkwd = CHKKWD | CHKALIAS;
567 		break;
568 	case TLP:
569 		n1 = (union node *)stalloc(sizeof (struct nredir));
570 		n1->type = NSUBSHELL;
571 		n1->nredir.n = list(0);
572 		n1->nredir.redirect = NULL;
573 		consumetoken(TRP);
574 		checkkwd = CHKKWD | CHKALIAS;
575 		is_subshell = 1;
576 		break;
577 	case TBEGIN:
578 		n1 = list(0);
579 		consumetoken(TEND);
580 		checkkwd = CHKKWD | CHKALIAS;
581 		break;
582 	/* A simple command must have at least one redirection or word. */
583 	case TBACKGND:
584 	case TSEMI:
585 	case TAND:
586 	case TOR:
587 	case TPIPE:
588 	case TENDCASE:
589 	case TFALLTHRU:
590 	case TEOF:
591 	case TNL:
592 	case TRP:
593 		if (!redir)
594 			synexpect(-1);
595 	case TWORD:
596 		tokpushback++;
597 		n1 = simplecmd(rpp, redir);
598 		return n1;
599 	default:
600 		synexpect(-1);
601 	}
602 
603 	/* Now check for redirection which may follow command */
604 	while (readtoken() == TREDIR) {
605 		*rpp = n2 = redirnode;
606 		rpp = &n2->nfile.next;
607 		parsefname();
608 	}
609 	tokpushback++;
610 	*rpp = NULL;
611 	if (redir) {
612 		if (!is_subshell) {
613 			n2 = (union node *)stalloc(sizeof (struct nredir));
614 			n2->type = NREDIR;
615 			n2->nredir.n = n1;
616 			n1 = n2;
617 		}
618 		n1->nredir.redirect = redir;
619 	}
620 
621 	return n1;
622 }
623 
624 
625 static union node *
626 simplecmd(union node **rpp, union node *redir)
627 {
628 	union node *args, **app;
629 	union node **orig_rpp = rpp;
630 	union node *n = NULL;
631 	int special;
632 	int savecheckkwd;
633 
634 	/* If we don't have any redirections already, then we must reset */
635 	/* rpp to be the address of the local redir variable.  */
636 	if (redir == NULL)
637 		rpp = &redir;
638 
639 	args = NULL;
640 	app = &args;
641 	/*
642 	 * We save the incoming value, because we need this for shell
643 	 * functions.  There can not be a redirect or an argument between
644 	 * the function name and the open parenthesis.
645 	 */
646 	orig_rpp = rpp;
647 
648 	savecheckkwd = CHKALIAS;
649 
650 	for (;;) {
651 		checkkwd = savecheckkwd;
652 		if (readtoken() == TWORD) {
653 			n = makename();
654 			*app = n;
655 			app = &n->narg.next;
656 			if (savecheckkwd != 0 && !isassignment(wordtext))
657 				savecheckkwd = 0;
658 		} else if (lasttoken == TREDIR) {
659 			*rpp = n = redirnode;
660 			rpp = &n->nfile.next;
661 			parsefname();	/* read name of redirection file */
662 		} else if (lasttoken == TLP && app == &args->narg.next
663 					    && rpp == orig_rpp) {
664 			/* We have a function */
665 			consumetoken(TRP);
666 			funclinno = plinno;
667 			/*
668 			 * - Require plain text.
669 			 * - Functions with '/' cannot be called.
670 			 * - Reject name=().
671 			 * - Reject ksh extended glob patterns.
672 			 */
673 			if (!noexpand(n->narg.text) || quoteflag ||
674 			    strchr(n->narg.text, '/') ||
675 			    strchr("!%*+-=?@}~",
676 				n->narg.text[strlen(n->narg.text) - 1]))
677 				synerror("Bad function name");
678 			rmescapes(n->narg.text);
679 			if (find_builtin(n->narg.text, &special) >= 0 &&
680 			    special)
681 				synerror("Cannot override a special builtin with a function");
682 			n->type = NDEFUN;
683 			n->narg.next = command();
684 			funclinno = 0;
685 			return n;
686 		} else {
687 			tokpushback++;
688 			break;
689 		}
690 	}
691 	*app = NULL;
692 	*rpp = NULL;
693 	n = (union node *)stalloc(sizeof (struct ncmd));
694 	n->type = NCMD;
695 	n->ncmd.args = args;
696 	n->ncmd.redirect = redir;
697 	return n;
698 }
699 
700 static union node *
701 makename(void)
702 {
703 	union node *n;
704 
705 	n = (union node *)stalloc(sizeof (struct narg));
706 	n->type = NARG;
707 	n->narg.next = NULL;
708 	n->narg.text = wordtext;
709 	n->narg.backquote = backquotelist;
710 	return n;
711 }
712 
713 static union node *
714 makebinary(int type, union node *n1, union node *n2)
715 {
716 	union node *n;
717 
718 	n = (union node *)stalloc(sizeof (struct nbinary));
719 	n->type = type;
720 	n->nbinary.ch1 = n1;
721 	n->nbinary.ch2 = n2;
722 	return (n);
723 }
724 
725 void
726 forcealias(void)
727 {
728 	checkkwd |= CHKALIAS;
729 }
730 
731 void
732 fixredir(union node *n, const char *text, int err)
733 {
734 	TRACE(("Fix redir %s %d\n", text, err));
735 	if (!err)
736 		n->ndup.vname = NULL;
737 
738 	if (is_digit(text[0]) && text[1] == '\0')
739 		n->ndup.dupfd = digit_val(text[0]);
740 	else if (text[0] == '-' && text[1] == '\0')
741 		n->ndup.dupfd = -1;
742 	else {
743 
744 		if (err)
745 			synerror("Bad fd number");
746 		else
747 			n->ndup.vname = makename();
748 	}
749 }
750 
751 
752 static void
753 parsefname(void)
754 {
755 	union node *n = redirnode;
756 
757 	consumetoken(TWORD);
758 	if (n->type == NHERE) {
759 		struct heredoc *here = heredoc;
760 		struct heredoc *p;
761 
762 		if (quoteflag == 0)
763 			n->type = NXHERE;
764 		TRACE(("Here document %d\n", n->type));
765 		if (here->striptabs) {
766 			while (*wordtext == '\t')
767 				wordtext++;
768 		}
769 		if (! noexpand(wordtext))
770 			synerror("Illegal eof marker for << redirection");
771 		rmescapes(wordtext);
772 		here->eofmark = wordtext;
773 		here->next = NULL;
774 		if (heredoclist == NULL)
775 			heredoclist = here;
776 		else {
777 			for (p = heredoclist ; p->next ; p = p->next);
778 			p->next = here;
779 		}
780 	} else if (n->type == NTOFD || n->type == NFROMFD) {
781 		fixredir(n, wordtext, 0);
782 	} else {
783 		n->nfile.fname = makename();
784 	}
785 }
786 
787 
788 /*
789  * Input any here documents.
790  */
791 
792 static void
793 parseheredoc(void)
794 {
795 	struct heredoc *here;
796 	union node *n;
797 
798 	while (heredoclist) {
799 		here = heredoclist;
800 		heredoclist = here->next;
801 		if (needprompt) {
802 			setprompt(2);
803 			needprompt = 0;
804 		}
805 		readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
806 				here->eofmark, here->striptabs);
807 		n = makename();
808 		here->here->nhere.doc = n;
809 	}
810 }
811 
812 static int
813 peektoken(void)
814 {
815 	int t;
816 
817 	t = readtoken();
818 	tokpushback++;
819 	return (t);
820 }
821 
822 static int
823 readtoken(void)
824 {
825 	int t;
826 	struct alias *ap;
827 #ifdef DEBUG
828 	int alreadyseen = tokpushback;
829 #endif
830 
831 	top:
832 	t = xxreadtoken();
833 
834 	/*
835 	 * eat newlines
836 	 */
837 	if (checkkwd & CHKNL) {
838 		while (t == TNL) {
839 			parseheredoc();
840 			t = xxreadtoken();
841 		}
842 	}
843 
844 	/*
845 	 * check for keywords and aliases
846 	 */
847 	if (t == TWORD && !quoteflag)
848 	{
849 		const char * const *pp;
850 
851 		if (checkkwd & CHKKWD)
852 			for (pp = parsekwd; *pp; pp++) {
853 				if (**pp == *wordtext && equal(*pp, wordtext))
854 				{
855 					lasttoken = t = pp - parsekwd + KWDOFFSET;
856 					TRACE(("keyword %s recognized\n", tokname[t]));
857 					goto out;
858 				}
859 			}
860 		if (checkkwd & CHKALIAS &&
861 		    (ap = lookupalias(wordtext, 1)) != NULL) {
862 			pushstring(ap->val, strlen(ap->val), ap);
863 			goto top;
864 		}
865 	}
866 out:
867 	if (t != TNOT)
868 		checkkwd = 0;
869 
870 #ifdef DEBUG
871 	if (!alreadyseen)
872 	    TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
873 	else
874 	    TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
875 #endif
876 	return (t);
877 }
878 
879 
880 /*
881  * Read the next input token.
882  * If the token is a word, we set backquotelist to the list of cmds in
883  *	backquotes.  We set quoteflag to true if any part of the word was
884  *	quoted.
885  * If the token is TREDIR, then we set redirnode to a structure containing
886  *	the redirection.
887  * In all cases, the variable startlinno is set to the number of the line
888  *	on which the token starts.
889  *
890  * [Change comment:  here documents and internal procedures]
891  * [Readtoken shouldn't have any arguments.  Perhaps we should make the
892  *  word parsing code into a separate routine.  In this case, readtoken
893  *  doesn't need to have any internal procedures, but parseword does.
894  *  We could also make parseoperator in essence the main routine, and
895  *  have parseword (readtoken1?) handle both words and redirection.]
896  */
897 
898 #define RETURN(token)	return lasttoken = token
899 
900 static int
901 xxreadtoken(void)
902 {
903 	int c;
904 
905 	if (tokpushback) {
906 		tokpushback = 0;
907 		return lasttoken;
908 	}
909 	if (needprompt) {
910 		setprompt(2);
911 		needprompt = 0;
912 	}
913 	startlinno = plinno;
914 	for (;;) {	/* until token or start of word found */
915 		c = pgetc_macro();
916 		switch (c) {
917 		case ' ': case '\t':
918 			continue;
919 		case '#':
920 			while ((c = pgetc()) != '\n' && c != PEOF);
921 			pungetc();
922 			continue;
923 		case '\\':
924 			if (pgetc() == '\n') {
925 				startlinno = ++plinno;
926 				if (doprompt)
927 					setprompt(2);
928 				else
929 					setprompt(0);
930 				continue;
931 			}
932 			pungetc();
933 			/* FALLTHROUGH */
934 		default:
935 			return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
936 		case '\n':
937 			plinno++;
938 			needprompt = doprompt;
939 			RETURN(TNL);
940 		case PEOF:
941 			RETURN(TEOF);
942 		case '&':
943 			if (pgetc_linecont() == '&')
944 				RETURN(TAND);
945 			pungetc();
946 			RETURN(TBACKGND);
947 		case '|':
948 			if (pgetc_linecont() == '|')
949 				RETURN(TOR);
950 			pungetc();
951 			RETURN(TPIPE);
952 		case ';':
953 			c = pgetc_linecont();
954 			if (c == ';')
955 				RETURN(TENDCASE);
956 			else if (c == '&')
957 				RETURN(TFALLTHRU);
958 			pungetc();
959 			RETURN(TSEMI);
960 		case '(':
961 			RETURN(TLP);
962 		case ')':
963 			RETURN(TRP);
964 		}
965 	}
966 #undef RETURN
967 }
968 
969 
970 #define MAXNEST_static 8
971 struct tokenstate
972 {
973 	const char *syntax; /* *SYNTAX */
974 	int parenlevel; /* levels of parentheses in arithmetic */
975 	enum tokenstate_category
976 	{
977 		TSTATE_TOP,
978 		TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
979 		TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
980 		TSTATE_ARITH
981 	} category;
982 };
983 
984 
985 /*
986  * Check to see whether we are at the end of the here document.  When this
987  * is called, c is set to the first character of the next input line.  If
988  * we are at the end of the here document, this routine sets the c to PEOF.
989  * The new value of c is returned.
990  */
991 
992 static int
993 checkend(int c, const char *eofmark, int striptabs)
994 {
995 	if (striptabs) {
996 		while (c == '\t')
997 			c = pgetc();
998 	}
999 	if (c == *eofmark) {
1000 		int c2;
1001 		const char *q;
1002 
1003 		for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
1004 			;
1005 		if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
1006 			c = PEOF;
1007 			if (c2 == '\n') {
1008 				plinno++;
1009 				needprompt = doprompt;
1010 			}
1011 		} else {
1012 			pungetc();
1013 			pushstring(eofmark + 1, q - (eofmark + 1), NULL);
1014 		}
1015 	} else if (c == '\n' && *eofmark == '\0') {
1016 		c = PEOF;
1017 		plinno++;
1018 		needprompt = doprompt;
1019 	}
1020 	return (c);
1021 }
1022 
1023 
1024 /*
1025  * Parse a redirection operator.  The variable "out" points to a string
1026  * specifying the fd to be redirected.  The variable "c" contains the
1027  * first character of the redirection operator.
1028  */
1029 
1030 static void
1031 parseredir(char *out, int c)
1032 {
1033 	char fd = *out;
1034 	union node *np;
1035 
1036 	np = (union node *)stalloc(sizeof (struct nfile));
1037 	if (c == '>') {
1038 		np->nfile.fd = 1;
1039 		c = pgetc_linecont();
1040 		if (c == '>')
1041 			np->type = NAPPEND;
1042 		else if (c == '&')
1043 			np->type = NTOFD;
1044 		else if (c == '|')
1045 			np->type = NCLOBBER;
1046 		else {
1047 			np->type = NTO;
1048 			pungetc();
1049 		}
1050 	} else {	/* c == '<' */
1051 		np->nfile.fd = 0;
1052 		c = pgetc_linecont();
1053 		if (c == '<') {
1054 			if (sizeof (struct nfile) != sizeof (struct nhere)) {
1055 				np = (union node *)stalloc(sizeof (struct nhere));
1056 				np->nfile.fd = 0;
1057 			}
1058 			np->type = NHERE;
1059 			heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
1060 			heredoc->here = np;
1061 			if ((c = pgetc_linecont()) == '-') {
1062 				heredoc->striptabs = 1;
1063 			} else {
1064 				heredoc->striptabs = 0;
1065 				pungetc();
1066 			}
1067 		} else if (c == '&')
1068 			np->type = NFROMFD;
1069 		else if (c == '>')
1070 			np->type = NFROMTO;
1071 		else {
1072 			np->type = NFROM;
1073 			pungetc();
1074 		}
1075 	}
1076 	if (fd != '\0')
1077 		np->nfile.fd = digit_val(fd);
1078 	redirnode = np;
1079 }
1080 
1081 /*
1082  * Called to parse command substitutions.
1083  */
1084 
1085 static char *
1086 parsebackq(char *out, struct nodelist **pbqlist,
1087 		int oldstyle, int dblquote, int quoted)
1088 {
1089 	struct nodelist **nlpp;
1090 	union node *n;
1091 	char *volatile str;
1092 	struct jmploc jmploc;
1093 	struct jmploc *const savehandler = handler;
1094 	size_t savelen;
1095 	int saveprompt;
1096 	const int bq_startlinno = plinno;
1097 	char *volatile ostr = NULL;
1098 	struct parsefile *const savetopfile = getcurrentfile();
1099 	struct heredoc *const saveheredoclist = heredoclist;
1100 	struct heredoc *here;
1101 
1102 	str = NULL;
1103 	if (setjmp(jmploc.loc)) {
1104 		popfilesupto(savetopfile);
1105 		if (str)
1106 			ckfree(str);
1107 		if (ostr)
1108 			ckfree(ostr);
1109 		heredoclist = saveheredoclist;
1110 		handler = savehandler;
1111 		if (exception == EXERROR) {
1112 			startlinno = bq_startlinno;
1113 			synerror("Error in command substitution");
1114 		}
1115 		longjmp(handler->loc, 1);
1116 	}
1117 	INTOFF;
1118 	savelen = out - stackblock();
1119 	if (savelen > 0) {
1120 		str = ckmalloc(savelen);
1121 		memcpy(str, stackblock(), savelen);
1122 	}
1123 	handler = &jmploc;
1124 	heredoclist = NULL;
1125 	INTON;
1126         if (oldstyle) {
1127                 /* We must read until the closing backquote, giving special
1128                    treatment to some slashes, and then push the string and
1129                    reread it as input, interpreting it normally.  */
1130                 char *oout;
1131                 int c;
1132                 int olen;
1133 
1134 
1135                 STARTSTACKSTR(oout);
1136 		for (;;) {
1137 			if (needprompt) {
1138 				setprompt(2);
1139 				needprompt = 0;
1140 			}
1141 			CHECKSTRSPACE(2, oout);
1142 			c = pgetc_linecont();
1143 			if (c == '`')
1144 				break;
1145 			switch (c) {
1146 			case '\\':
1147 				c = pgetc();
1148                                 if (c != '\\' && c != '`' && c != '$'
1149                                     && (!dblquote || c != '"'))
1150                                         USTPUTC('\\', oout);
1151 				break;
1152 
1153 			case '\n':
1154 				plinno++;
1155 				needprompt = doprompt;
1156 				break;
1157 
1158 			case PEOF:
1159 			        startlinno = plinno;
1160 				synerror("EOF in backquote substitution");
1161  				break;
1162 
1163 			default:
1164 				break;
1165 			}
1166 			USTPUTC(c, oout);
1167                 }
1168                 USTPUTC('\0', oout);
1169                 olen = oout - stackblock();
1170 		INTOFF;
1171 		ostr = ckmalloc(olen);
1172 		memcpy(ostr, stackblock(), olen);
1173 		setinputstring(ostr, 1);
1174 		INTON;
1175         }
1176 	nlpp = pbqlist;
1177 	while (*nlpp)
1178 		nlpp = &(*nlpp)->next;
1179 	*nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
1180 	(*nlpp)->next = NULL;
1181 
1182 	if (oldstyle) {
1183 		saveprompt = doprompt;
1184 		doprompt = 0;
1185 	}
1186 
1187 	n = list(0);
1188 
1189 	if (oldstyle) {
1190 		if (peektoken() != TEOF)
1191 			synexpect(-1);
1192 		doprompt = saveprompt;
1193 	} else
1194 		consumetoken(TRP);
1195 
1196 	(*nlpp)->n = n;
1197         if (oldstyle) {
1198 		/*
1199 		 * Start reading from old file again, ignoring any pushed back
1200 		 * tokens left from the backquote parsing
1201 		 */
1202                 popfile();
1203 		tokpushback = 0;
1204 	}
1205 	STARTSTACKSTR(out);
1206 	CHECKSTRSPACE(savelen + 1, out);
1207 	INTOFF;
1208 	if (str) {
1209 		memcpy(out, str, savelen);
1210 		STADJUST(savelen, out);
1211 		ckfree(str);
1212 		str = NULL;
1213 	}
1214 	if (ostr) {
1215 		ckfree(ostr);
1216 		ostr = NULL;
1217 	}
1218 	here = saveheredoclist;
1219 	if (here != NULL) {
1220 		while (here->next != NULL)
1221 			here = here->next;
1222 		here->next = heredoclist;
1223 		heredoclist = saveheredoclist;
1224 	}
1225 	handler = savehandler;
1226 	INTON;
1227 	if (quoted)
1228 		USTPUTC(CTLBACKQ | CTLQUOTE, out);
1229 	else
1230 		USTPUTC(CTLBACKQ, out);
1231 	return out;
1232 }
1233 
1234 
1235 /*
1236  * Called to parse a backslash escape sequence inside $'...'.
1237  * The backslash has already been read.
1238  */
1239 static char *
1240 readcstyleesc(char *out)
1241 {
1242 	int c, vc, i, n;
1243 	unsigned int v;
1244 
1245 	c = pgetc();
1246 	switch (c) {
1247 	case '\0':
1248 		synerror("Unterminated quoted string");
1249 	case '\n':
1250 		plinno++;
1251 		if (doprompt)
1252 			setprompt(2);
1253 		else
1254 			setprompt(0);
1255 		return out;
1256 	case '\\':
1257 	case '\'':
1258 	case '"':
1259 		v = c;
1260 		break;
1261 	case 'a': v = '\a'; break;
1262 	case 'b': v = '\b'; break;
1263 	case 'e': v = '\033'; break;
1264 	case 'f': v = '\f'; break;
1265 	case 'n': v = '\n'; break;
1266 	case 'r': v = '\r'; break;
1267 	case 't': v = '\t'; break;
1268 	case 'v': v = '\v'; break;
1269 	case 'x':
1270 		  v = 0;
1271 		  for (;;) {
1272 			  c = pgetc();
1273 			  if (c >= '0' && c <= '9')
1274 				  v = (v << 4) + c - '0';
1275 			  else if (c >= 'A' && c <= 'F')
1276 				  v = (v << 4) + c - 'A' + 10;
1277 			  else if (c >= 'a' && c <= 'f')
1278 				  v = (v << 4) + c - 'a' + 10;
1279 			  else
1280 				  break;
1281 		  }
1282 		  pungetc();
1283 		  break;
1284 	case '0': case '1': case '2': case '3':
1285 	case '4': case '5': case '6': case '7':
1286 		  v = c - '0';
1287 		  c = pgetc();
1288 		  if (c >= '0' && c <= '7') {
1289 			  v <<= 3;
1290 			  v += c - '0';
1291 			  c = pgetc();
1292 			  if (c >= '0' && c <= '7') {
1293 				  v <<= 3;
1294 				  v += c - '0';
1295 			  } else
1296 				  pungetc();
1297 		  } else
1298 			  pungetc();
1299 		  break;
1300 	case 'c':
1301 		  c = pgetc();
1302 		  if (c < 0x3f || c > 0x7a || c == 0x60)
1303 			  synerror("Bad escape sequence");
1304 		  if (c == '\\' && pgetc() != '\\')
1305 			  synerror("Bad escape sequence");
1306 		  if (c == '?')
1307 			  v = 127;
1308 		  else
1309 			  v = c & 0x1f;
1310 		  break;
1311 	case 'u':
1312 	case 'U':
1313 		  n = c == 'U' ? 8 : 4;
1314 		  v = 0;
1315 		  for (i = 0; i < n; i++) {
1316 			  c = pgetc();
1317 			  if (c >= '0' && c <= '9')
1318 				  v = (v << 4) + c - '0';
1319 			  else if (c >= 'A' && c <= 'F')
1320 				  v = (v << 4) + c - 'A' + 10;
1321 			  else if (c >= 'a' && c <= 'f')
1322 				  v = (v << 4) + c - 'a' + 10;
1323 			  else
1324 				  synerror("Bad escape sequence");
1325 		  }
1326 		  if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
1327 			  synerror("Bad escape sequence");
1328 		  /* We really need iconv here. */
1329 		  if (initial_localeisutf8 && v > 127) {
1330 			  CHECKSTRSPACE(4, out);
1331 			  /*
1332 			   * We cannot use wctomb() as the locale may have
1333 			   * changed.
1334 			   */
1335 			  if (v <= 0x7ff) {
1336 				  USTPUTC(0xc0 | v >> 6, out);
1337 				  USTPUTC(0x80 | (v & 0x3f), out);
1338 				  return out;
1339 			  } else if (v <= 0xffff) {
1340 				  USTPUTC(0xe0 | v >> 12, out);
1341 				  USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1342 				  USTPUTC(0x80 | (v & 0x3f), out);
1343 				  return out;
1344 			  } else if (v <= 0x10ffff) {
1345 				  USTPUTC(0xf0 | v >> 18, out);
1346 				  USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1347 				  USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1348 				  USTPUTC(0x80 | (v & 0x3f), out);
1349 				  return out;
1350 			  }
1351 		  }
1352 		  if (v > 127)
1353 			  v = '?';
1354 		  break;
1355 	default:
1356 		  synerror("Bad escape sequence");
1357 	}
1358 	vc = (char)v;
1359 	/*
1360 	 * We can't handle NUL bytes.
1361 	 * POSIX says we should skip till the closing quote.
1362 	 */
1363 	if (vc == '\0') {
1364 		while ((c = pgetc()) != '\'') {
1365 			if (c == '\\')
1366 				c = pgetc();
1367 			if (c == PEOF)
1368 				synerror("Unterminated quoted string");
1369 			if (c == '\n') {
1370 				plinno++;
1371 				if (doprompt)
1372 					setprompt(2);
1373 				else
1374 					setprompt(0);
1375 			}
1376 		}
1377 		pungetc();
1378 		return out;
1379 	}
1380 	if (SQSYNTAX[vc] == CCTL)
1381 		USTPUTC(CTLESC, out);
1382 	USTPUTC(vc, out);
1383 	return out;
1384 }
1385 
1386 
1387 /*
1388  * If eofmark is NULL, read a word or a redirection symbol.  If eofmark
1389  * is not NULL, read a here document.  In the latter case, eofmark is the
1390  * word which marks the end of the document and striptabs is true if
1391  * leading tabs should be stripped from the document.  The argument firstc
1392  * is the first character of the input token or document.
1393  *
1394  * Because C does not have internal subroutines, I have simulated them
1395  * using goto's to implement the subroutine linkage.  The following macros
1396  * will run code that appears at the end of readtoken1.
1397  */
1398 
1399 #define PARSESUB()	{goto parsesub; parsesub_return:;}
1400 #define	PARSEARITH()	{goto parsearith; parsearith_return:;}
1401 
1402 static int
1403 readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
1404     int striptabs)
1405 {
1406 	int c = firstc;
1407 	char *out;
1408 	int len;
1409 	struct nodelist *bqlist;
1410 	int quotef;
1411 	int newvarnest;
1412 	int level;
1413 	int synentry;
1414 	struct tokenstate state_static[MAXNEST_static];
1415 	int maxnest = MAXNEST_static;
1416 	struct tokenstate *state = state_static;
1417 	int sqiscstyle = 0;
1418 
1419 	startlinno = plinno;
1420 	quotef = 0;
1421 	bqlist = NULL;
1422 	newvarnest = 0;
1423 	level = 0;
1424 	state[level].syntax = initialsyntax;
1425 	state[level].parenlevel = 0;
1426 	state[level].category = TSTATE_TOP;
1427 
1428 	STARTSTACKSTR(out);
1429 	loop: {	/* for each line, until end of word */
1430 		if (eofmark && eofmark != NOEOFMARK)
1431 			/* set c to PEOF if at end of here document */
1432 			c = checkend(c, eofmark, striptabs);
1433 		for (;;) {	/* until end of line or end of word */
1434 			CHECKSTRSPACE(4, out);	/* permit 4 calls to USTPUTC */
1435 
1436 			synentry = state[level].syntax[c];
1437 
1438 			switch(synentry) {
1439 			case CNL:	/* '\n' */
1440 				if (level == 0)
1441 					goto endword;	/* exit outer loop */
1442 				/* FALLTHROUGH */
1443 			case CQNL:
1444 				USTPUTC(c, out);
1445 				plinno++;
1446 				if (doprompt)
1447 					setprompt(2);
1448 				else
1449 					setprompt(0);
1450 				c = pgetc();
1451 				goto loop;		/* continue outer loop */
1452 			case CSBACK:
1453 				if (sqiscstyle) {
1454 					out = readcstyleesc(out);
1455 					break;
1456 				}
1457 				/* FALLTHROUGH */
1458 			case CWORD:
1459 				USTPUTC(c, out);
1460 				break;
1461 			case CCTL:
1462 				if (eofmark == NULL || initialsyntax != SQSYNTAX)
1463 					USTPUTC(CTLESC, out);
1464 				USTPUTC(c, out);
1465 				break;
1466 			case CBACK:	/* backslash */
1467 				c = pgetc();
1468 				if (c == PEOF) {
1469 					USTPUTC('\\', out);
1470 					pungetc();
1471 				} else if (c == '\n') {
1472 					plinno++;
1473 					if (doprompt)
1474 						setprompt(2);
1475 					else
1476 						setprompt(0);
1477 				} else {
1478 					if (state[level].syntax == DQSYNTAX &&
1479 					    c != '\\' && c != '`' && c != '$' &&
1480 					    (c != '"' || (eofmark != NULL &&
1481 						newvarnest == 0)) &&
1482 					    (c != '}' || state[level].category != TSTATE_VAR_OLD))
1483 						USTPUTC('\\', out);
1484 					if ((eofmark == NULL ||
1485 					    newvarnest > 0) &&
1486 					    state[level].syntax == BASESYNTAX)
1487 						USTPUTC(CTLQUOTEMARK, out);
1488 					if (SQSYNTAX[c] == CCTL)
1489 						USTPUTC(CTLESC, out);
1490 					USTPUTC(c, out);
1491 					if ((eofmark == NULL ||
1492 					    newvarnest > 0) &&
1493 					    state[level].syntax == BASESYNTAX &&
1494 					    state[level].category == TSTATE_VAR_OLD)
1495 						USTPUTC(CTLQUOTEEND, out);
1496 					quotef++;
1497 				}
1498 				break;
1499 			case CSQUOTE:
1500 				USTPUTC(CTLQUOTEMARK, out);
1501 				state[level].syntax = SQSYNTAX;
1502 				sqiscstyle = 0;
1503 				break;
1504 			case CDQUOTE:
1505 				USTPUTC(CTLQUOTEMARK, out);
1506 				state[level].syntax = DQSYNTAX;
1507 				break;
1508 			case CENDQUOTE:
1509 				if (eofmark != NULL && newvarnest == 0)
1510 					USTPUTC(c, out);
1511 				else {
1512 					if (state[level].category == TSTATE_VAR_OLD)
1513 						USTPUTC(CTLQUOTEEND, out);
1514 					state[level].syntax = BASESYNTAX;
1515 					quotef++;
1516 				}
1517 				break;
1518 			case CVAR:	/* '$' */
1519 				PARSESUB();		/* parse substitution */
1520 				break;
1521 			case CENDVAR:	/* '}' */
1522 				if (level > 0 &&
1523 				    ((state[level].category == TSTATE_VAR_OLD &&
1524 				      state[level].syntax ==
1525 				      state[level - 1].syntax) ||
1526 				    (state[level].category == TSTATE_VAR_NEW &&
1527 				     state[level].syntax == BASESYNTAX))) {
1528 					if (state[level].category == TSTATE_VAR_NEW)
1529 						newvarnest--;
1530 					level--;
1531 					USTPUTC(CTLENDVAR, out);
1532 				} else {
1533 					USTPUTC(c, out);
1534 				}
1535 				break;
1536 			case CLP:	/* '(' in arithmetic */
1537 				state[level].parenlevel++;
1538 				USTPUTC(c, out);
1539 				break;
1540 			case CRP:	/* ')' in arithmetic */
1541 				if (state[level].parenlevel > 0) {
1542 					USTPUTC(c, out);
1543 					--state[level].parenlevel;
1544 				} else {
1545 					if (pgetc_linecont() == ')') {
1546 						if (level > 0 &&
1547 						    state[level].category == TSTATE_ARITH) {
1548 							level--;
1549 							USTPUTC(CTLENDARI, out);
1550 						} else
1551 							USTPUTC(')', out);
1552 					} else {
1553 						/*
1554 						 * unbalanced parens
1555 						 *  (don't 2nd guess - no error)
1556 						 */
1557 						pungetc();
1558 						USTPUTC(')', out);
1559 					}
1560 				}
1561 				break;
1562 			case CBQUOTE:	/* '`' */
1563 				out = parsebackq(out, &bqlist, 1,
1564 				    state[level].syntax == DQSYNTAX &&
1565 				    (eofmark == NULL || newvarnest > 0),
1566 				    state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
1567 				break;
1568 			case CEOF:
1569 				goto endword;		/* exit outer loop */
1570 			case CIGN:
1571 				break;
1572 			default:
1573 				if (level == 0)
1574 					goto endword;	/* exit outer loop */
1575 				USTPUTC(c, out);
1576 			}
1577 			c = pgetc_macro();
1578 		}
1579 	}
1580 endword:
1581 	if (state[level].syntax == ARISYNTAX)
1582 		synerror("Missing '))'");
1583 	if (state[level].syntax != BASESYNTAX && eofmark == NULL)
1584 		synerror("Unterminated quoted string");
1585 	if (state[level].category == TSTATE_VAR_OLD ||
1586 	    state[level].category == TSTATE_VAR_NEW) {
1587 		startlinno = plinno;
1588 		synerror("Missing '}'");
1589 	}
1590 	if (state != state_static)
1591 		parser_temp_free_upto(state);
1592 	USTPUTC('\0', out);
1593 	len = out - stackblock();
1594 	out = stackblock();
1595 	if (eofmark == NULL) {
1596 		if ((c == '>' || c == '<')
1597 		 && quotef == 0
1598 		 && len <= 2
1599 		 && (*out == '\0' || is_digit(*out))) {
1600 			parseredir(out, c);
1601 			return lasttoken = TREDIR;
1602 		} else {
1603 			pungetc();
1604 		}
1605 	}
1606 	quoteflag = quotef;
1607 	backquotelist = bqlist;
1608 	grabstackblock(len);
1609 	wordtext = out;
1610 	return lasttoken = TWORD;
1611 /* end of readtoken routine */
1612 
1613 
1614 /*
1615  * Parse a substitution.  At this point, we have read the dollar sign
1616  * and nothing else.
1617  */
1618 
1619 parsesub: {
1620 	int subtype;
1621 	int typeloc;
1622 	int flags;
1623 	char *p;
1624 	static const char types[] = "}-+?=";
1625 	int linno;
1626 	int length;
1627 	int c1;
1628 
1629 	c = pgetc_linecont();
1630 	if (c == '(') {	/* $(command) or $((arith)) */
1631 		if (pgetc_linecont() == '(') {
1632 			PARSEARITH();
1633 		} else {
1634 			pungetc();
1635 			out = parsebackq(out, &bqlist, 0,
1636 			    state[level].syntax == DQSYNTAX &&
1637 			    (eofmark == NULL || newvarnest > 0),
1638 			    state[level].syntax == DQSYNTAX ||
1639 			    state[level].syntax == ARISYNTAX);
1640 		}
1641 	} else if (c == '{' || is_name(c) || is_special(c)) {
1642 		USTPUTC(CTLVAR, out);
1643 		typeloc = out - stackblock();
1644 		USTPUTC(VSNORMAL, out);
1645 		subtype = VSNORMAL;
1646 		flags = 0;
1647 		if (c == '{') {
1648 			c = pgetc_linecont();
1649 			subtype = 0;
1650 		}
1651 varname:
1652 		if (!is_eof(c) && is_name(c)) {
1653 			length = 0;
1654 			do {
1655 				STPUTC(c, out);
1656 				c = pgetc_linecont();
1657 				length++;
1658 			} while (!is_eof(c) && is_in_name(c));
1659 			if (length == 6 &&
1660 			    strncmp(out - length, "LINENO", length) == 0) {
1661 				/* Replace the variable name with the
1662 				 * current line number. */
1663 				STADJUST(-6, out);
1664 				CHECKSTRSPACE(11, out);
1665 				linno = plinno;
1666 				if (funclinno != 0)
1667 					linno -= funclinno - 1;
1668 				length = snprintf(out, 11, "%d", linno);
1669 				if (length > 10)
1670 					length = 10;
1671 				out += length;
1672 				flags |= VSLINENO;
1673 			}
1674 		} else if (is_digit(c)) {
1675 			if (subtype != VSNORMAL) {
1676 				do {
1677 					STPUTC(c, out);
1678 					c = pgetc_linecont();
1679 				} while (is_digit(c));
1680 			} else {
1681 				USTPUTC(c, out);
1682 				c = pgetc_linecont();
1683 			}
1684 		} else if (is_special(c)) {
1685 			c1 = c;
1686 			c = pgetc_linecont();
1687 			if (subtype == 0 && c1 == '#') {
1688 				subtype = VSLENGTH;
1689 				if (strchr(types, c) == NULL && c != ':' &&
1690 				    c != '#' && c != '%')
1691 					goto varname;
1692 				c1 = c;
1693 				c = pgetc_linecont();
1694 				if (c1 != '}' && c == '}') {
1695 					pungetc();
1696 					c = c1;
1697 					goto varname;
1698 				}
1699 				pungetc();
1700 				c = c1;
1701 				c1 = '#';
1702 				subtype = 0;
1703 			}
1704 			USTPUTC(c1, out);
1705 		} else {
1706 			subtype = VSERROR;
1707 			if (c == '}')
1708 				pungetc();
1709 			else if (c == '\n' || c == PEOF)
1710 				synerror("Unexpected end of line in substitution");
1711 			else if (BASESYNTAX[c] != CCTL)
1712 				USTPUTC(c, out);
1713 		}
1714 		if (subtype == 0) {
1715 			switch (c) {
1716 			case ':':
1717 				flags |= VSNUL;
1718 				c = pgetc_linecont();
1719 				/*FALLTHROUGH*/
1720 			default:
1721 				p = strchr(types, c);
1722 				if (p == NULL) {
1723 					if (c == '\n' || c == PEOF)
1724 						synerror("Unexpected end of line in substitution");
1725 					if (flags == VSNUL)
1726 						STPUTC(':', out);
1727 					if (BASESYNTAX[c] != CCTL)
1728 						STPUTC(c, out);
1729 					subtype = VSERROR;
1730 				} else
1731 					subtype = p - types + VSNORMAL;
1732 				break;
1733 			case '%':
1734 			case '#':
1735 				{
1736 					int cc = c;
1737 					subtype = c == '#' ? VSTRIMLEFT :
1738 							     VSTRIMRIGHT;
1739 					c = pgetc_linecont();
1740 					if (c == cc)
1741 						subtype++;
1742 					else
1743 						pungetc();
1744 					break;
1745 				}
1746 			}
1747 		} else if (subtype != VSERROR) {
1748 			if (subtype == VSLENGTH && c != '}')
1749 				subtype = VSERROR;
1750 			pungetc();
1751 		}
1752 		STPUTC('=', out);
1753 		if (state[level].syntax == DQSYNTAX ||
1754 		    state[level].syntax == ARISYNTAX)
1755 			flags |= VSQUOTE;
1756 		*(stackblock() + typeloc) = subtype | flags;
1757 		if (subtype != VSNORMAL) {
1758 			if (level + 1 >= maxnest) {
1759 				maxnest *= 2;
1760 				if (state == state_static) {
1761 					state = parser_temp_alloc(
1762 					    maxnest * sizeof(*state));
1763 					memcpy(state, state_static,
1764 					    MAXNEST_static * sizeof(*state));
1765 				} else
1766 					state = parser_temp_realloc(state,
1767 					    maxnest * sizeof(*state));
1768 			}
1769 			level++;
1770 			state[level].parenlevel = 0;
1771 			if (subtype == VSMINUS || subtype == VSPLUS ||
1772 			    subtype == VSQUESTION || subtype == VSASSIGN) {
1773 				/*
1774 				 * For operators that were in the Bourne shell,
1775 				 * inherit the double-quote state.
1776 				 */
1777 				state[level].syntax = state[level - 1].syntax;
1778 				state[level].category = TSTATE_VAR_OLD;
1779 			} else {
1780 				/*
1781 				 * The other operators take a pattern,
1782 				 * so go to BASESYNTAX.
1783 				 * Also, ' and " are now special, even
1784 				 * in here documents.
1785 				 */
1786 				state[level].syntax = BASESYNTAX;
1787 				state[level].category = TSTATE_VAR_NEW;
1788 				newvarnest++;
1789 			}
1790 		}
1791 	} else if (c == '\'' && state[level].syntax == BASESYNTAX) {
1792 		/* $'cstylequotes' */
1793 		USTPUTC(CTLQUOTEMARK, out);
1794 		state[level].syntax = SQSYNTAX;
1795 		sqiscstyle = 1;
1796 	} else {
1797 		USTPUTC('$', out);
1798 		pungetc();
1799 	}
1800 	goto parsesub_return;
1801 }
1802 
1803 
1804 /*
1805  * Parse an arithmetic expansion (indicate start of one and set state)
1806  */
1807 parsearith: {
1808 
1809 	if (level + 1 >= maxnest) {
1810 		maxnest *= 2;
1811 		if (state == state_static) {
1812 			state = parser_temp_alloc(
1813 			    maxnest * sizeof(*state));
1814 			memcpy(state, state_static,
1815 			    MAXNEST_static * sizeof(*state));
1816 		} else
1817 			state = parser_temp_realloc(state,
1818 			    maxnest * sizeof(*state));
1819 	}
1820 	level++;
1821 	state[level].syntax = ARISYNTAX;
1822 	state[level].parenlevel = 0;
1823 	state[level].category = TSTATE_ARITH;
1824 	USTPUTC(CTLARI, out);
1825 	if (state[level - 1].syntax == DQSYNTAX)
1826 		USTPUTC('"',out);
1827 	else
1828 		USTPUTC(' ',out);
1829 	goto parsearith_return;
1830 }
1831 
1832 } /* end of readtoken */
1833 
1834 
1835 /*
1836  * Returns true if the text contains nothing to expand (no dollar signs
1837  * or backquotes).
1838  */
1839 
1840 static int
1841 noexpand(char *text)
1842 {
1843 	char *p;
1844 	char c;
1845 
1846 	p = text;
1847 	while ((c = *p++) != '\0') {
1848 		if ( c == CTLQUOTEMARK)
1849 			continue;
1850 		if (c == CTLESC)
1851 			p++;
1852 		else if (BASESYNTAX[(int)c] == CCTL)
1853 			return 0;
1854 	}
1855 	return 1;
1856 }
1857 
1858 
1859 /*
1860  * Return true if the argument is a legal variable name (a letter or
1861  * underscore followed by zero or more letters, underscores, and digits).
1862  */
1863 
1864 int
1865 goodname(const char *name)
1866 {
1867 	const char *p;
1868 
1869 	p = name;
1870 	if (! is_name(*p))
1871 		return 0;
1872 	while (*++p) {
1873 		if (! is_in_name(*p))
1874 			return 0;
1875 	}
1876 	return 1;
1877 }
1878 
1879 
1880 int
1881 isassignment(const char *p)
1882 {
1883 	if (!is_name(*p))
1884 		return 0;
1885 	p++;
1886 	for (;;) {
1887 		if (*p == '=')
1888 			return 1;
1889 		else if (!is_in_name(*p))
1890 			return 0;
1891 		p++;
1892 	}
1893 }
1894 
1895 
1896 static void
1897 consumetoken(int token)
1898 {
1899 	if (readtoken() != token)
1900 		synexpect(token);
1901 }
1902 
1903 
1904 /*
1905  * Called when an unexpected token is read during the parse.  The argument
1906  * is the token that is expected, or -1 if more than one type of token can
1907  * occur at this point.
1908  */
1909 
1910 static void
1911 synexpect(int token)
1912 {
1913 	char msg[64];
1914 
1915 	if (token >= 0) {
1916 		fmtstr(msg, 64, "%s unexpected (expecting %s)",
1917 			tokname[lasttoken], tokname[token]);
1918 	} else {
1919 		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
1920 	}
1921 	synerror(msg);
1922 }
1923 
1924 
1925 static void
1926 synerror(const char *msg)
1927 {
1928 	if (commandname)
1929 		outfmt(out2, "%s: %d: ", commandname, startlinno);
1930 	else if (arg0)
1931 		outfmt(out2, "%s: ", arg0);
1932 	outfmt(out2, "Syntax error: %s\n", msg);
1933 	error((char *)NULL);
1934 }
1935 
1936 static void
1937 setprompt(int which)
1938 {
1939 	whichprompt = which;
1940 	if (which == 0)
1941 		return;
1942 
1943 #ifndef NO_HISTORY
1944 	if (!el)
1945 #endif
1946 	{
1947 		out2str(getprompt(NULL));
1948 		flushout(out2);
1949 	}
1950 }
1951 
1952 static int
1953 pgetc_linecont(void)
1954 {
1955 	int c;
1956 
1957 	while ((c = pgetc_macro()) == '\\') {
1958 		c = pgetc();
1959 		if (c == '\n') {
1960 			plinno++;
1961 			if (doprompt)
1962 				setprompt(2);
1963 			else
1964 				setprompt(0);
1965 		} else {
1966 			pungetc();
1967 			/* Allow the backslash to be pushed back. */
1968 			pushstring("\\", 1, NULL);
1969 			return (pgetc());
1970 		}
1971 	}
1972 	return (c);
1973 }
1974 
1975 
1976 static struct passwd *
1977 getpwlogin(void)
1978 {
1979 	const char *login;
1980 
1981 	login = getlogin();
1982 	if (login == NULL)
1983 		return (NULL);
1984 
1985 	return (getpwnam(login));
1986 }
1987 
1988 
1989 static void
1990 getusername(char *name, size_t namelen)
1991 {
1992 	static char cached_name[MAXLOGNAME];
1993 	struct passwd *pw;
1994 	uid_t euid;
1995 
1996 	if (cached_name[0] == '\0') {
1997 		euid = geteuid();
1998 
1999 		/*
2000 		 * Handle the case when there is more than one
2001 		 * login with the same UID, or when the login
2002 		 * returned by getlogin(2) does no longer match
2003 		 * the current UID.
2004 		 */
2005 		pw = getpwlogin();
2006 		if (pw == NULL || pw->pw_uid != euid)
2007 			pw = getpwuid(euid);
2008 
2009 		if (pw != NULL) {
2010 			strlcpy(cached_name, pw->pw_name,
2011 			    sizeof(cached_name));
2012 		} else {
2013 			snprintf(cached_name, sizeof(cached_name),
2014 			    "%u", euid);
2015 		}
2016 	}
2017 
2018 	strlcpy(name, cached_name, namelen);
2019 }
2020 
2021 
2022 /*
2023  * called by editline -- any expansions to the prompt
2024  *    should be added here.
2025  */
2026 char *
2027 getprompt(void *unused __unused)
2028 {
2029 	static char ps[PROMPTLEN];
2030 	const char *fmt;
2031 	const char *home;
2032 	const char *pwd;
2033 	size_t homelen;
2034 	int i, trim;
2035 	static char internal_error[] = "??";
2036 
2037 	/*
2038 	 * Select prompt format.
2039 	 */
2040 	switch (whichprompt) {
2041 	case 0:
2042 		fmt = "";
2043 		break;
2044 	case 1:
2045 		fmt = ps1val();
2046 		break;
2047 	case 2:
2048 		fmt = ps2val();
2049 		break;
2050 	default:
2051 		return internal_error;
2052 	}
2053 
2054 	/*
2055 	 * Format prompt string.
2056 	 */
2057 	for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++)
2058 		if (*fmt == '\\')
2059 			switch (*++fmt) {
2060 
2061 				/*
2062 				 * Hostname.
2063 				 *
2064 				 * \h specifies just the local hostname,
2065 				 * \H specifies fully-qualified hostname.
2066 				 */
2067 			case 'h':
2068 			case 'H':
2069 				ps[i] = '\0';
2070 				gethostname(&ps[i], PROMPTLEN - i - 1);
2071 				ps[PROMPTLEN - 1] = '\0';
2072 				/* Skip to end of hostname. */
2073 				trim = (*fmt == 'h') ? '.' : '\0';
2074 				while ((ps[i] != '\0') && (ps[i] != trim))
2075 					i++;
2076 				--i;
2077 				break;
2078 
2079 				/*
2080 				 * User name.
2081 				 */
2082 			case 'u':
2083 				ps[i] = '\0';
2084 				getusername(&ps[i], PROMPTLEN - i);
2085 				/* Skip to end of username. */
2086 				while (ps[i + 1] != '\0')
2087 					i++;
2088 				break;
2089 
2090 				/*
2091 				 * Working directory.
2092 				 *
2093 				 * \W specifies just the final component,
2094 				 * \w specifies the entire path.
2095 				 */
2096 			case 'W':
2097 			case 'w':
2098 				pwd = lookupvar("PWD");
2099 				if (pwd == NULL || *pwd == '\0')
2100 					pwd = "?";
2101 				if (*fmt == 'W' &&
2102 				    *pwd == '/' && pwd[1] != '\0')
2103 					strlcpy(&ps[i], strrchr(pwd, '/') + 1,
2104 					    PROMPTLEN - i);
2105 				else {
2106 					home = lookupvar("HOME");
2107 					if (home != NULL)
2108 						homelen = strlen(home);
2109 					if (home != NULL &&
2110 					    strcmp(home, "/") != 0 &&
2111 					    strncmp(pwd, home, homelen) == 0 &&
2112 					    (pwd[homelen] == '/' ||
2113 					    pwd[homelen] == '\0')) {
2114 						strlcpy(&ps[i], "~",
2115 						    PROMPTLEN - i);
2116 						strlcpy(&ps[i + 1],
2117 						    pwd + homelen,
2118 						    PROMPTLEN - i - 1);
2119 					} else {
2120 						strlcpy(&ps[i], pwd, PROMPTLEN - i);
2121 					}
2122 				}
2123 				/* Skip to end of path. */
2124 				while (ps[i + 1] != '\0')
2125 					i++;
2126 				break;
2127 
2128 				/*
2129 				 * Superuser status.
2130 				 *
2131 				 * '$' for normal users, '#' for root.
2132 				 */
2133 			case '$':
2134 				ps[i] = (geteuid() != 0) ? '$' : '#';
2135 				break;
2136 
2137 				/*
2138 				 * A literal \.
2139 				 */
2140 			case '\\':
2141 				ps[i] = '\\';
2142 				break;
2143 
2144 				/*
2145 				 * Emit unrecognized formats verbatim.
2146 				 */
2147 			default:
2148 				ps[i] = '\\';
2149 				if (i < PROMPTLEN - 2)
2150 					ps[++i] = *fmt;
2151 				break;
2152 			}
2153 		else
2154 			ps[i] = *fmt;
2155 	ps[i] = '\0';
2156 	return (ps);
2157 }
2158 
2159 
2160 const char *
2161 expandstr(const char *ps)
2162 {
2163 	union node n;
2164 	struct jmploc jmploc;
2165 	struct jmploc *const savehandler = handler;
2166 	const int saveprompt = doprompt;
2167 	struct parsefile *const savetopfile = getcurrentfile();
2168 	struct parser_temp *const saveparser_temp = parser_temp;
2169 	const char *result = NULL;
2170 
2171 	if (!setjmp(jmploc.loc)) {
2172 		handler = &jmploc;
2173 		parser_temp = NULL;
2174 		setinputstring(ps, 1);
2175 		doprompt = 0;
2176 		readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
2177 		if (backquotelist != NULL)
2178 			error("Command substitution not allowed here");
2179 
2180 		n.narg.type = NARG;
2181 		n.narg.next = NULL;
2182 		n.narg.text = wordtext;
2183 		n.narg.backquote = backquotelist;
2184 
2185 		expandarg(&n, NULL, 0);
2186 		result = stackblock();
2187 		INTOFF;
2188 	}
2189 	handler = savehandler;
2190 	doprompt = saveprompt;
2191 	popfilesupto(savetopfile);
2192 	if (parser_temp != saveparser_temp) {
2193 		parser_temp_free_all();
2194 		parser_temp = saveparser_temp;
2195 	}
2196 	if (result != NULL) {
2197 		INTON;
2198 	} else if (exception == EXINT)
2199 		raise(SIGINT);
2200 	return result;
2201 }
2202