parser.c revision 1.155 1 /* $NetBSD: parser.c,v 1.155 2018/12/01 07:02:23 kre Exp $ */
2
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95";
39 #else
40 __RCSID("$NetBSD: parser.c,v 1.155 2018/12/01 07:02:23 kre Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <limits.h>
47
48 #include "shell.h"
49 #include "parser.h"
50 #include "nodes.h"
51 #include "expand.h" /* defines rmescapes() */
52 #include "eval.h" /* defines commandname */
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 #ifndef SMALL
64 #include "myhistedit.h"
65 #endif
66
67 /*
68 * Shell command parser.
69 */
70
71 /* values returned by readtoken */
72 #include "token.h"
73
74 #define OPENBRACE '{'
75 #define CLOSEBRACE '}'
76
77 struct HereDoc {
78 struct HereDoc *next; /* next here document in list */
79 union node *here; /* redirection node */
80 char *eofmark; /* string indicating end of input */
81 int striptabs; /* if set, strip leading tabs */
82 int startline; /* line number where << seen */
83 };
84
85 MKINIT struct parse_state parse_state;
86 union parse_state_p psp = { .c_current_parser = &parse_state };
87
88 static const struct parse_state init_parse_state = { /* all 0's ... */
89 .ps_noalias = 0,
90 .ps_heredoclist = NULL,
91 .ps_parsebackquote = 0,
92 .ps_doprompt = 0,
93 .ps_needprompt = 0,
94 .ps_lasttoken = 0,
95 .ps_tokpushback = 0,
96 .ps_wordtext = NULL,
97 .ps_checkkwd = 0,
98 .ps_redirnode = NULL,
99 .ps_heredoc = NULL,
100 .ps_quoteflag = 0,
101 .ps_startlinno = 0,
102 .ps_funclinno = 0,
103 .ps_elided_nl = 0,
104 };
105
106 STATIC union node *list(int);
107 STATIC union node *andor(void);
108 STATIC union node *pipeline(void);
109 STATIC union node *command(void);
110 STATIC union node *simplecmd(union node **, union node *);
111 STATIC union node *makeword(int);
112 STATIC void parsefname(void);
113 STATIC int slurp_heredoc(char *const, const int, const int);
114 STATIC void readheredocs(void);
115 STATIC int peektoken(void);
116 STATIC int readtoken(void);
117 STATIC int xxreadtoken(void);
118 STATIC int readtoken1(int, char const *, int);
119 STATIC int noexpand(char *);
120 STATIC void linebreak(void);
121 STATIC void consumetoken(int);
122 STATIC void synexpect(int, const char *) __dead;
123 STATIC void synerror(const char *) __dead;
124 STATIC void setprompt(int);
125 STATIC int pgetc_linecont(void);
126
127 static const char EOFhere[] = "EOF reading here (<<) document";
128
129 #ifdef DEBUG
130 int parsing = 0;
131 #endif
132
133 /*
134 * Read and parse a command. Returns NEOF on end of file. (NULL is a
135 * valid parse tree indicating a blank line.)
136 */
137
138 union node *
139 parsecmd(int interact)
140 {
141 int t;
142 union node *n;
143
144 #ifdef DEBUG
145 parsing++;
146 #endif
147 tokpushback = 0;
148 checkkwd = 0;
149 doprompt = interact;
150 if (doprompt)
151 setprompt(1);
152 else
153 setprompt(0);
154 needprompt = 0;
155 t = readtoken();
156 #ifdef DEBUG
157 parsing--;
158 #endif
159 if (t == TEOF)
160 return NEOF;
161 if (t == TNL)
162 return NULL;
163
164 #ifdef DEBUG
165 parsing++;
166 #endif
167 tokpushback++;
168 n = list(1);
169 #ifdef DEBUG
170 parsing--;
171 #endif
172 if (heredoclist)
173 error("%d: Here document (<<%s) expected but not present",
174 heredoclist->startline, heredoclist->eofmark);
175 return n;
176 }
177
178
179 STATIC union node *
180 list(int nlflag)
181 {
182 union node *ntop, *n1, *n2, *n3;
183 int tok;
184
185 CTRACE(DBG_PARSE, ("list(%d): entered @%d\n",nlflag,plinno));
186
187 checkkwd = 2;
188 if (nlflag == 0 && tokendlist[peektoken()])
189 return NULL;
190 ntop = n1 = NULL;
191 for (;;) {
192 n2 = andor();
193 tok = readtoken();
194 if (tok == TBACKGND) {
195 if (n2->type == NCMD || n2->type == NPIPE)
196 n2->ncmd.backgnd = 1;
197 else if (n2->type == NREDIR)
198 n2->type = NBACKGND;
199 else {
200 n3 = stalloc(sizeof(struct nredir));
201 n3->type = NBACKGND;
202 n3->nredir.n = n2;
203 n3->nredir.redirect = NULL;
204 n2 = n3;
205 }
206 }
207
208 if (ntop == NULL)
209 ntop = n2;
210 else if (n1 == NULL) {
211 n1 = stalloc(sizeof(struct nbinary));
212 n1->type = NSEMI;
213 n1->nbinary.ch1 = ntop;
214 n1->nbinary.ch2 = n2;
215 ntop = n1;
216 } else {
217 n3 = stalloc(sizeof(struct nbinary));
218 n3->type = NSEMI;
219 n3->nbinary.ch1 = n1->nbinary.ch2;
220 n3->nbinary.ch2 = n2;
221 n1->nbinary.ch2 = n3;
222 n1 = n3;
223 }
224
225 switch (tok) {
226 case TBACKGND:
227 case TSEMI:
228 tok = readtoken();
229 /* FALLTHROUGH */
230 case TNL:
231 if (tok == TNL) {
232 readheredocs();
233 if (nlflag)
234 return ntop;
235 } else if (tok == TEOF && nlflag)
236 return ntop;
237 else
238 tokpushback++;
239
240 checkkwd = 2;
241 if (!nlflag && tokendlist[peektoken()])
242 return ntop;
243 break;
244 case TEOF:
245 pungetc(); /* push back EOF on input */
246 return ntop;
247 default:
248 if (nlflag)
249 synexpect(-1, 0);
250 tokpushback++;
251 return ntop;
252 }
253 }
254 }
255
256 STATIC union node *
257 andor(void)
258 {
259 union node *n1, *n2, *n3;
260 int t;
261
262 CTRACE(DBG_PARSE, ("andor: entered @%d\n", plinno));
263
264 n1 = pipeline();
265 for (;;) {
266 if ((t = readtoken()) == TAND) {
267 t = NAND;
268 } else if (t == TOR) {
269 t = NOR;
270 } else {
271 tokpushback++;
272 return n1;
273 }
274 n2 = pipeline();
275 n3 = stalloc(sizeof(struct nbinary));
276 n3->type = t;
277 n3->nbinary.ch1 = n1;
278 n3->nbinary.ch2 = n2;
279 n1 = n3;
280 }
281 }
282
283 STATIC union node *
284 pipeline(void)
285 {
286 union node *n1, *n2, *pipenode;
287 struct nodelist *lp, *prev;
288 int negate;
289
290 CTRACE(DBG_PARSE, ("pipeline: entered @%d\n", plinno));
291
292 negate = 0;
293 checkkwd = 2;
294 while (readtoken() == TNOT) {
295 CTRACE(DBG_PARSE, ("pipeline: TNOT recognized\n"));
296 #ifndef BOGUS_NOT_COMMAND
297 if (posix && negate)
298 synerror("2nd \"!\" unexpected");
299 #endif
300 negate++;
301 }
302 tokpushback++;
303 n1 = command();
304 if (readtoken() == TPIPE) {
305 pipenode = stalloc(sizeof(struct npipe));
306 pipenode->type = NPIPE;
307 pipenode->npipe.backgnd = 0;
308 lp = stalloc(sizeof(struct nodelist));
309 pipenode->npipe.cmdlist = lp;
310 lp->n = n1;
311 do {
312 prev = lp;
313 lp = stalloc(sizeof(struct nodelist));
314 lp->n = command();
315 prev->next = lp;
316 } while (readtoken() == TPIPE);
317 lp->next = NULL;
318 n1 = pipenode;
319 }
320 tokpushback++;
321 if (negate) {
322 CTRACE(DBG_PARSE, ("%snegate pipeline\n",
323 (negate&1) ? "" : "double "));
324 n2 = stalloc(sizeof(struct nnot));
325 n2->type = (negate & 1) ? NNOT : NDNOT;
326 n2->nnot.com = n1;
327 return n2;
328 } else
329 return n1;
330 }
331
332
333
334 STATIC union node *
335 command(void)
336 {
337 union node *n1, *n2;
338 union node *ap, **app;
339 union node *cp, **cpp;
340 union node *redir, **rpp;
341 int t;
342 #ifdef BOGUS_NOT_COMMAND
343 int negate = 0;
344 #endif
345
346 CTRACE(DBG_PARSE, ("command: entered @%d\n", plinno));
347
348 checkkwd = 2;
349 redir = NULL;
350 n1 = NULL;
351 rpp = &redir;
352
353 /* Check for redirection which may precede command */
354 while (readtoken() == TREDIR) {
355 *rpp = n2 = redirnode;
356 rpp = &n2->nfile.next;
357 parsefname();
358 }
359 tokpushback++;
360
361 #ifdef BOGUS_NOT_COMMAND /* only in pileline() */
362 while (readtoken() == TNOT) {
363 CTRACE(DBG_PARSE, ("command: TNOT (bogus) recognized\n"));
364 negate++;
365 }
366 tokpushback++;
367 #endif
368
369 switch (readtoken()) {
370 case TIF:
371 n1 = stalloc(sizeof(struct nif));
372 n1->type = NIF;
373 n1->nif.test = list(0);
374 consumetoken(TTHEN);
375 n1->nif.ifpart = list(0);
376 n2 = n1;
377 while (readtoken() == TELIF) {
378 n2->nif.elsepart = stalloc(sizeof(struct nif));
379 n2 = n2->nif.elsepart;
380 n2->type = NIF;
381 n2->nif.test = list(0);
382 consumetoken(TTHEN);
383 n2->nif.ifpart = list(0);
384 }
385 if (lasttoken == TELSE)
386 n2->nif.elsepart = list(0);
387 else {
388 n2->nif.elsepart = NULL;
389 tokpushback++;
390 }
391 consumetoken(TFI);
392 checkkwd = 1;
393 break;
394 case TWHILE:
395 case TUNTIL:
396 n1 = stalloc(sizeof(struct nbinary));
397 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
398 n1->nbinary.ch1 = list(0);
399 consumetoken(TDO);
400 n1->nbinary.ch2 = list(0);
401 consumetoken(TDONE);
402 checkkwd = 1;
403 break;
404 case TFOR:
405 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
406 synerror("Bad for loop variable");
407 n1 = stalloc(sizeof(struct nfor));
408 n1->type = NFOR;
409 n1->nfor.var = wordtext;
410 linebreak();
411 if (lasttoken==TWORD && !quoteflag && equal(wordtext,"in")) {
412 app = ≈
413 while (readtoken() == TWORD) {
414 n2 = makeword(startlinno);
415 *app = n2;
416 app = &n2->narg.next;
417 }
418 *app = NULL;
419 n1->nfor.args = ap;
420 if (lasttoken != TNL && lasttoken != TSEMI)
421 synexpect(TSEMI, 0);
422 } else {
423 static char argvars[5] = {
424 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
425 };
426
427 n2 = stalloc(sizeof(struct narg));
428 n2->type = NARG;
429 n2->narg.text = argvars;
430 n2->narg.backquote = NULL;
431 n2->narg.next = NULL;
432 n2->narg.lineno = startlinno;
433 n1->nfor.args = n2;
434 /*
435 * Newline or semicolon here is optional (but note
436 * that the original Bourne shell only allowed NL).
437 */
438 if (lasttoken != TNL && lasttoken != TSEMI)
439 tokpushback++;
440 }
441 checkkwd = 2;
442 if ((t = readtoken()) == TDO)
443 t = TDONE;
444 else if (t == TBEGIN)
445 t = TEND;
446 else
447 synexpect(TDO, 0);
448 n1->nfor.body = list(0);
449 consumetoken(t);
450 checkkwd = 1;
451 break;
452 case TCASE:
453 n1 = stalloc(sizeof(struct ncase));
454 n1->type = NCASE;
455 n1->ncase.lineno = startlinno - elided_nl;
456 consumetoken(TWORD);
457 n1->ncase.expr = makeword(startlinno);
458 linebreak();
459 if (lasttoken != TWORD || !equal(wordtext, "in"))
460 synexpect(-1, "in");
461 cpp = &n1->ncase.cases;
462 noalias = 1;
463 checkkwd = 2;
464 readtoken();
465 /*
466 * Both ksh and bash accept 'case x in esac'
467 * so configure scripts started taking advantage of this.
468 * The page: http://pubs.opengroup.org/onlinepubs/\
469 * 009695399/utilities/xcu_chap02.html contradicts itself,
470 * as to if this is legal; the "Case Conditional Format"
471 * paragraph shows one case is required, but the "Grammar"
472 * section shows a grammar that explicitly allows the no
473 * case option.
474 *
475 * The standard also says (section 2.10):
476 * This formal syntax shall take precedence over the
477 * preceding text syntax description.
478 * ie: the "Grammar" section wins. The text is just
479 * a rough guide (introduction to the common case.)
480 */
481 while (lasttoken != TESAC) {
482 *cpp = cp = stalloc(sizeof(struct nclist));
483 cp->type = NCLIST;
484 app = &cp->nclist.pattern;
485 if (lasttoken == TLP)
486 readtoken();
487 for (;;) {
488 if (lasttoken < TWORD)
489 synexpect(TWORD, 0);
490 *app = ap = makeword(startlinno);
491 checkkwd = 2;
492 if (readtoken() != TPIPE)
493 break;
494 app = &ap->narg.next;
495 readtoken();
496 }
497 noalias = 0;
498 if (lasttoken != TRP)
499 synexpect(TRP, 0);
500 cp->nclist.lineno = startlinno;
501 cp->nclist.body = list(0);
502
503 checkkwd = 2;
504 if ((t = readtoken()) != TESAC) {
505 if (t != TENDCASE && t != TCASEFALL) {
506 noalias = 0;
507 synexpect(TENDCASE, 0);
508 } else {
509 if (t == TCASEFALL)
510 cp->type = NCLISTCONT;
511 noalias = 1;
512 checkkwd = 2;
513 readtoken();
514 }
515 }
516 cpp = &cp->nclist.next;
517 }
518 noalias = 0;
519 *cpp = NULL;
520 checkkwd = 1;
521 break;
522 case TLP:
523 n1 = stalloc(sizeof(struct nredir));
524 n1->type = NSUBSHELL;
525 n1->nredir.n = list(0);
526 n1->nredir.redirect = NULL;
527 if (n1->nredir.n == NULL)
528 synexpect(-1, 0);
529 consumetoken(TRP);
530 checkkwd = 1;
531 break;
532 case TBEGIN:
533 n1 = list(0);
534 if (posix && n1 == NULL)
535 synexpect(-1, 0);
536 consumetoken(TEND);
537 checkkwd = 1;
538 break;
539
540 case TBACKGND:
541 case TSEMI:
542 case TAND:
543 case TOR:
544 case TPIPE:
545 case TNL:
546 case TEOF:
547 case TRP:
548 case TENDCASE:
549 case TCASEFALL:
550 /*
551 * simple commands must have something in them,
552 * either a word (which at this point includes a=b)
553 * or a redirection. If we reached the end of the
554 * command (which one of these tokens indicates)
555 * when we are just starting, and have not had a
556 * redirect, then ...
557 *
558 * nb: it is still possible to end up with empty
559 * simple commands, if the "command" is a var
560 * expansion that produces nothing:
561 * X= ; $X && $X
562 * --> &&
563 * That is OK and is handled after word expansions.
564 */
565 if (!redir)
566 synexpect(-1, 0);
567 /*
568 * continue to build a node containing the redirect.
569 * the tokpushback means that our ending token will be
570 * read again in simplecmd, causing it to terminate,
571 * so only the redirect(s) will be contained in the
572 * returned n1
573 */
574 /* FALLTHROUGH */
575 case TWORD:
576 tokpushback++;
577 n1 = simplecmd(rpp, redir);
578 goto checkneg;
579 default:
580 synexpect(-1, 0);
581 /* NOTREACHED */
582 }
583
584 /* Now check for redirection which may follow command */
585 while (readtoken() == TREDIR) {
586 *rpp = n2 = redirnode;
587 rpp = &n2->nfile.next;
588 parsefname();
589 }
590 tokpushback++;
591 *rpp = NULL;
592 if (redir) {
593 if (n1 == NULL || n1->type != NSUBSHELL) {
594 n2 = stalloc(sizeof(struct nredir));
595 n2->type = NREDIR;
596 n2->nredir.n = n1;
597 n1 = n2;
598 }
599 n1->nredir.redirect = redir;
600 }
601
602 checkneg:
603 #ifdef BOGUS_NOT_COMMAND
604 if (negate) {
605 VTRACE(DBG_PARSE, ("bogus %snegate command\n",
606 (negate&1) ? "" : "double "));
607 n2 = stalloc(sizeof(struct nnot));
608 n2->type = (negate & 1) ? NNOT : NDNOT;
609 n2->nnot.com = n1;
610 return n2;
611 }
612 else
613 #endif
614 return n1;
615 }
616
617
618 STATIC union node *
619 simplecmd(union node **rpp, union node *redir)
620 {
621 union node *args, **app;
622 union node *n = NULL;
623 int line = 0;
624 #ifdef BOGUS_NOT_COMMAND
625 union node *n2;
626 int negate = 0;
627 #endif
628
629 CTRACE(DBG_PARSE, ("simple command with%s redir already @%d\n",
630 redir ? "" : "out", plinno));
631
632 /* If we don't have any redirections already, then we must reset */
633 /* rpp to be the address of the local redir variable. */
634 if (redir == 0)
635 rpp = &redir;
636
637 args = NULL;
638 app = &args;
639
640 #ifdef BOGUS_NOT_COMMAND /* pipelines get negated, commands do not */
641 while (readtoken() == TNOT) {
642 VTRACE(DBG_PARSE, ("simplcmd: bogus TNOT recognized\n"));
643 negate++;
644 }
645 tokpushback++;
646 #endif
647
648 for (;;) {
649 if (readtoken() == TWORD) {
650 if (line == 0)
651 line = startlinno;
652 n = makeword(startlinno);
653 *app = n;
654 app = &n->narg.next;
655 } else if (lasttoken == TREDIR) {
656 if (line == 0)
657 line = startlinno;
658 *rpp = n = redirnode;
659 rpp = &n->nfile.next;
660 parsefname(); /* read name of redirection file */
661 } else if (lasttoken == TLP && app == &args->narg.next
662 && redir == 0) {
663 /* We have a function */
664 consumetoken(TRP);
665 funclinno = plinno;
666 rmescapes(n->narg.text);
667 if (strchr(n->narg.text, '/'))
668 synerror("Bad function name");
669 VTRACE(DBG_PARSE, ("Function '%s' seen @%d\n",
670 n->narg.text, plinno));
671 n->type = NDEFUN;
672 n->narg.lineno = plinno - elided_nl;
673 n->narg.next = command();
674 funclinno = 0;
675 goto checkneg;
676 } else {
677 tokpushback++;
678 break;
679 }
680 }
681
682 if (args == NULL && redir == NULL)
683 synexpect(-1, 0);
684 *app = NULL;
685 *rpp = NULL;
686 n = stalloc(sizeof(struct ncmd));
687 n->type = NCMD;
688 n->ncmd.lineno = line - elided_nl;
689 n->ncmd.backgnd = 0;
690 n->ncmd.args = args;
691 n->ncmd.redirect = redir;
692 n->ncmd.lineno = startlinno;
693
694 checkneg:
695 #ifdef BOGUS_NOT_COMMAND
696 if (negate) {
697 VTRACE(DBG_PARSE, ("bogus %snegate simplecmd\n",
698 (negate&1) ? "" : "double "));
699 n2 = stalloc(sizeof(struct nnot));
700 n2->type = (negate & 1) ? NNOT : NDNOT;
701 n2->nnot.com = n;
702 return n2;
703 }
704 else
705 #endif
706 return n;
707 }
708
709 STATIC union node *
710 makeword(int lno)
711 {
712 union node *n;
713
714 n = stalloc(sizeof(struct narg));
715 n->type = NARG;
716 n->narg.next = NULL;
717 n->narg.text = wordtext;
718 n->narg.backquote = backquotelist;
719 n->narg.lineno = lno;
720 return n;
721 }
722
723 void
724 fixredir(union node *n, const char *text, int err)
725 {
726
727 VTRACE(DBG_PARSE, ("Fix redir %s %d\n", text, err));
728 if (!err)
729 n->ndup.vname = NULL;
730
731 if (is_number(text))
732 n->ndup.dupfd = number(text);
733 else if (text[0] == '-' && text[1] == '\0')
734 n->ndup.dupfd = -1;
735 else {
736
737 if (err)
738 synerror("Bad fd number");
739 else
740 n->ndup.vname = makeword(startlinno - elided_nl);
741 }
742 }
743
744
745 STATIC void
746 parsefname(void)
747 {
748 union node *n = redirnode;
749
750 if (readtoken() != TWORD)
751 synexpect(-1, 0);
752 if (n->type == NHERE) {
753 struct HereDoc *here = heredoc;
754 struct HereDoc *p;
755
756 if (quoteflag == 0)
757 n->type = NXHERE;
758 VTRACE(DBG_PARSE, ("Here document %d @%d\n", n->type, plinno));
759 if (here->striptabs) {
760 while (*wordtext == '\t')
761 wordtext++;
762 }
763
764 /*
765 * this test is not really necessary, we are not
766 * required to expand wordtext, but there's no reason
767 * it cannot be $$ or something like that - that would
768 * not mean the pid, but literally two '$' characters.
769 * There is no need for limits on what the word can be.
770 * However, it needs to stay literal as entered, not
771 * have $ converted to CTLVAR or something, which as
772 * the parser is, at the minute, is impossible to prevent.
773 * So, leave it like this until the rest of the parser is fixed.
774 */
775 if (!noexpand(wordtext))
776 synerror("Illegal eof marker for << redirection");
777
778 rmescapes(wordtext);
779 here->eofmark = wordtext;
780 here->next = NULL;
781 if (heredoclist == NULL)
782 heredoclist = here;
783 else {
784 for (p = heredoclist ; p->next ; p = p->next)
785 continue;
786 p->next = here;
787 }
788 } else if (n->type == NTOFD || n->type == NFROMFD) {
789 fixredir(n, wordtext, 0);
790 } else {
791 n->nfile.fname = makeword(startlinno - elided_nl);
792 }
793 }
794
795 /*
796 * Check to see whether we are at the end of the here document. When this
797 * is called, c is set to the first character of the next input line. If
798 * we are at the end of the here document, this routine sets the c to PEOF.
799 * The new value of c is returned.
800 */
801
802 static int
803 checkend(int c, char * const eofmark, const int striptabs)
804 {
805
806 if (striptabs) {
807 while (c == '\t')
808 c = pgetc();
809 }
810 if (c == PEOF) {
811 if (*eofmark == '\0')
812 return (c);
813 synerror(EOFhere);
814 }
815 if (c == *eofmark) {
816 int c2;
817 char *q;
818
819 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
820 if (c2 == '\n') {
821 plinno++;
822 needprompt = doprompt;
823 }
824 if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
825 c = PEOF;
826 if (c2 == '\n') {
827 plinno++;
828 needprompt = doprompt;
829 }
830 } else {
831 pungetc();
832 pushstring(eofmark + 1, q - (eofmark + 1), NULL);
833 }
834 } else if (c == '\n' && *eofmark == '\0') {
835 c = PEOF;
836 plinno++;
837 needprompt = doprompt;
838 }
839 return (c);
840 }
841
842
843 /*
844 * Input any here documents.
845 */
846
847 STATIC int
848 slurp_heredoc(char *const eofmark, const int striptabs, const int sq)
849 {
850 int c;
851 char *out;
852 int lines = plinno;
853
854 c = pgetc();
855
856 /*
857 * If we hit EOF on the input, and the eofmark is a null string ('')
858 * we consider this empty line to be the eofmark, and exit without err.
859 */
860 if (c == PEOF && *eofmark != '\0')
861 synerror(EOFhere);
862
863 STARTSTACKSTR(out);
864
865 while ((c = checkend(c, eofmark, striptabs)) != PEOF) {
866 do {
867 if (sq) {
868 /*
869 * in single quoted mode (eofmark quoted)
870 * all we look for is \n so we can check
871 * for the epfmark - everything saved literally.
872 */
873 STPUTC(c, out);
874 if (c == '\n') {
875 plinno++;
876 break;
877 }
878 continue;
879 }
880 /*
881 * In double quoted (non-quoted eofmark)
882 * we must handle \ followed by \n here
883 * otherwise we can mismatch the end mark.
884 * All other uses of \ will be handled later
885 * when the here doc is expanded.
886 *
887 * This also makes sure \\ followed by \n does
888 * not suppress the newline (the \ quotes itself)
889 */
890 if (c == '\\') { /* A backslash */
891 STPUTC(c, out);
892 c = pgetc(); /* followed by */
893 if (c == '\n') { /* a newline? */
894 STPUTC(c, out);
895 plinno++;
896 continue; /* don't break */
897 }
898 }
899 STPUTC(c, out); /* keep the char */
900 if (c == '\n') { /* at end of line */
901 plinno++;
902 break; /* look for eofmark */
903 }
904 } while ((c = pgetc()) != PEOF);
905
906 /*
907 * If we have read a line, and reached EOF, without
908 * finding the eofmark, whether the EOF comes before
909 * or immediately after the \n, that is an error.
910 */
911 if (c == PEOF || (c = pgetc()) == PEOF)
912 synerror(EOFhere);
913 }
914 STPUTC('\0', out);
915
916 c = out - stackblock();
917 out = stackblock();
918 grabstackblock(c);
919 wordtext = out;
920
921 VTRACE(DBG_PARSE,
922 ("Slurped a %d line %sheredoc (to '%s')%s: len %d, \"%.*s%s\" @%d\n",
923 plinno - lines, sq ? "quoted " : "", eofmark,
924 striptabs ? " tab stripped" : "", c, (c > 16 ? 16 : c),
925 wordtext, (c > 16 ? "..." : ""), plinno));
926
927 return (plinno - lines);
928 }
929
930 static char *
931 insert_elided_nl(char *str)
932 {
933 while (elided_nl > 0) {
934 STPUTC(CTLNONL, str);
935 elided_nl--;
936 }
937 return str;
938 }
939
940 STATIC void
941 readheredocs(void)
942 {
943 struct HereDoc *here;
944 union node *n;
945 int line, l;
946
947 line = 0; /*XXX - gcc! obviously unneeded */
948 if (heredoclist)
949 line = heredoclist->startline + 1;
950 l = 0;
951 while (heredoclist) {
952 line += l;
953 here = heredoclist;
954 heredoclist = here->next;
955 if (needprompt) {
956 setprompt(2);
957 needprompt = 0;
958 }
959
960 l = slurp_heredoc(here->eofmark, here->striptabs,
961 here->here->nhere.type == NHERE);
962
963 here->here->nhere.doc = n = makeword(line);
964
965 if (here->here->nhere.type == NHERE)
966 continue;
967
968 /*
969 * Now "parse" here docs that have unquoted eofmarkers.
970 */
971 setinputstring(wordtext, 1, line);
972 VTRACE(DBG_PARSE, ("Reprocessing %d line here doc from %d\n",
973 l, line));
974 readtoken1(pgetc(), DQSYNTAX, 1);
975 n->narg.text = wordtext;
976 n->narg.backquote = backquotelist;
977 popfile();
978 }
979 }
980
981 STATIC int
982 peektoken(void)
983 {
984 int t;
985
986 t = readtoken();
987 tokpushback++;
988 return (t);
989 }
990
991 STATIC int
992 readtoken(void)
993 {
994 int t;
995 int savecheckkwd = checkkwd;
996 #ifdef DEBUG
997 int alreadyseen = tokpushback;
998 #endif
999 struct alias *ap;
1000
1001 top:
1002 t = xxreadtoken();
1003
1004 if (checkkwd) {
1005 /*
1006 * eat newlines
1007 */
1008 if (checkkwd == 2) {
1009 checkkwd = 0;
1010 while (t == TNL) {
1011 readheredocs();
1012 t = xxreadtoken();
1013 }
1014 } else
1015 checkkwd = 0;
1016 /*
1017 * check for keywords and aliases
1018 */
1019 if (t == TWORD && !quoteflag) {
1020 const char *const *pp;
1021
1022 for (pp = parsekwd; *pp; pp++) {
1023 if (**pp == *wordtext && equal(*pp, wordtext)) {
1024 lasttoken = t = pp -
1025 parsekwd + KWDOFFSET;
1026 VTRACE(DBG_PARSE,
1027 ("keyword %s recognized @%d\n",
1028 tokname[t], plinno));
1029 goto out;
1030 }
1031 }
1032 if (!noalias &&
1033 (ap = lookupalias(wordtext, 1)) != NULL) {
1034 VTRACE(DBG_PARSE,
1035 ("alias '%s' recognized -> <:%s:>\n",
1036 wordtext, ap->val));
1037 pushstring(ap->val, strlen(ap->val), ap);
1038 checkkwd = savecheckkwd;
1039 goto top;
1040 }
1041 }
1042 out:
1043 checkkwd = (t == TNOT) ? savecheckkwd : 0;
1044 }
1045 VTRACE(DBG_PARSE, ("%stoken %s %s @%d\n", alreadyseen ? "reread " : "",
1046 tokname[t], t == TWORD ? wordtext : "", plinno));
1047 return (t);
1048 }
1049
1050
1051 /*
1052 * Read the next input token.
1053 * If the token is a word, we set backquotelist to the list of cmds in
1054 * backquotes. We set quoteflag to true if any part of the word was
1055 * quoted.
1056 * If the token is TREDIR, then we set redirnode to a structure containing
1057 * the redirection.
1058 * In all cases, the variable startlinno is set to the number of the line
1059 * on which the token starts.
1060 *
1061 * [Change comment: here documents and internal procedures]
1062 * [Readtoken shouldn't have any arguments. Perhaps we should make the
1063 * word parsing code into a separate routine. In this case, readtoken
1064 * doesn't need to have any internal procedures, but parseword does.
1065 * We could also make parseoperator in essence the main routine, and
1066 * have parseword (readtoken1?) handle both words and redirection.]
1067 */
1068
1069 #define RETURN(token) return lasttoken = token
1070
1071 STATIC int
1072 xxreadtoken(void)
1073 {
1074 int c;
1075
1076 if (tokpushback) {
1077 tokpushback = 0;
1078 return lasttoken;
1079 }
1080 if (needprompt) {
1081 setprompt(2);
1082 needprompt = 0;
1083 }
1084 elided_nl = 0;
1085 startlinno = plinno;
1086 for (;;) { /* until token or start of word found */
1087 c = pgetc_macro();
1088 switch (c) {
1089 case ' ': case '\t':
1090 continue;
1091 case '#':
1092 while ((c = pgetc()) != '\n' && c != PEOF)
1093 continue;
1094 pungetc();
1095 continue;
1096
1097 case '\n':
1098 plinno++;
1099 needprompt = doprompt;
1100 RETURN(TNL);
1101 case PEOF:
1102 RETURN(TEOF);
1103
1104 case '&':
1105 if (pgetc_linecont() == '&')
1106 RETURN(TAND);
1107 pungetc();
1108 RETURN(TBACKGND);
1109 case '|':
1110 if (pgetc_linecont() == '|')
1111 RETURN(TOR);
1112 pungetc();
1113 RETURN(TPIPE);
1114 case ';':
1115 switch (pgetc_linecont()) {
1116 case ';':
1117 RETURN(TENDCASE);
1118 case '&':
1119 RETURN(TCASEFALL);
1120 default:
1121 pungetc();
1122 RETURN(TSEMI);
1123 }
1124 case '(':
1125 RETURN(TLP);
1126 case ')':
1127 RETURN(TRP);
1128
1129 case '\\':
1130 switch (pgetc()) {
1131 case '\n':
1132 startlinno = ++plinno;
1133 if (doprompt)
1134 setprompt(2);
1135 else
1136 setprompt(0);
1137 continue;
1138 case PEOF:
1139 RETURN(TEOF);
1140 default:
1141 pungetc();
1142 break;
1143 }
1144 /* FALLTHROUGH */
1145 default:
1146 return readtoken1(c, BASESYNTAX, 0);
1147 }
1148 }
1149 #undef RETURN
1150 }
1151
1152
1153
1154 /*
1155 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
1156 * is not NULL, read a here document. In the latter case, eofmark is the
1157 * word which marks the end of the document and striptabs is true if
1158 * leading tabs should be stripped from the document. The argument firstc
1159 * is the first character of the input token or document.
1160 *
1161 * Because C does not have internal subroutines, I have simulated them
1162 * using goto's to implement the subroutine linkage. The following macros
1163 * will run code that appears at the end of readtoken1.
1164 */
1165
1166 /*
1167 * We used to remember only the current syntax, variable nesting level,
1168 * double quote state for each var nesting level, and arith nesting
1169 * level (unrelated to var nesting) and one prev syntax when in arith
1170 * syntax. This worked for simple cases, but can't handle arith inside
1171 * var expansion inside arith inside var with some quoted and some not.
1172 *
1173 * Inspired by FreeBSD's implementation (though it was the obvious way)
1174 * though implemented differently, we now have a stack that keeps track
1175 * of what we are doing now, and what we were doing previously.
1176 * Every time something changes, which will eventually end and should
1177 * revert to the previous state, we push this stack, and then pop it
1178 * again later (that is every ${} with an operator (to parse the word
1179 * or pattern that follows) ${x} and $x are too simple to need it)
1180 * $(( )) $( ) and "...". Always. Really, always!
1181 *
1182 * The stack is implemented as one static (on the C stack) base block
1183 * containing LEVELS_PER_BLOCK (8) stack entries, which should be
1184 * enough for the vast majority of cases. For torture tests, we
1185 * malloc more blocks as needed. All accesses through the inline
1186 * functions below.
1187 */
1188
1189 /*
1190 * varnest & arinest will typically be 0 or 1
1191 * (varnest can increment in usages like ${x=${y}} but probably
1192 * does not really need to)
1193 * parenlevel allows balancing parens inside a $(( )), it is reset
1194 * at each new nesting level ( $(( ( x + 3 ${unset-)} )) does not work.
1195 * quoted is special - we need to know 2 things ... are we inside "..."
1196 * (even if inherited from some previous nesting level) and was there
1197 * an opening '"' at this level (so the next will be closing).
1198 * "..." can span nesting levels, but cannot be opened in one and
1199 * closed in a different one.
1200 * To handle this, "quoted" has two fields, the bottom 4 (really 2)
1201 * bits are 0, 1, or 2, for un, single, and double quoted (single quoted
1202 * is really so special that this setting is not very important)
1203 * and 0x10 that indicates that an opening quote has been seen.
1204 * The bottom 4 bits are inherited, the 0x10 bit is not.
1205 */
1206 struct tokenstate {
1207 const char *ts_syntax;
1208 unsigned short ts_parenlevel; /* counters */
1209 unsigned short ts_varnest; /* 64000 levels should be enough! */
1210 unsigned short ts_arinest;
1211 unsigned short ts_quoted; /* 1 -> single, 2 -> double */
1212 };
1213
1214 #define NQ 0x00 /* Unquoted */
1215 #define SQ 0x01 /* Single Quotes */
1216 #define DQ 0x02 /* Double Quotes (or equivalent) */
1217 #define CQ 0x03 /* C style Single Quotes */
1218 #define QF 0x0F /* Mask to extract previous values */
1219 #define QS 0x10 /* Quoting started at this level in stack */
1220
1221 #define LEVELS_PER_BLOCK 8
1222 #define VSS struct statestack
1223
1224 struct statestack {
1225 VSS *prev; /* previous block in list */
1226 int cur; /* which of our tokenstates is current */
1227 struct tokenstate tokenstate[LEVELS_PER_BLOCK];
1228 };
1229
1230 static inline struct tokenstate *
1231 currentstate(VSS *stack)
1232 {
1233 return &stack->tokenstate[stack->cur];
1234 }
1235
1236 static inline struct tokenstate *
1237 prevstate(VSS *stack)
1238 {
1239 if (stack->cur != 0)
1240 return &stack->tokenstate[stack->cur - 1];
1241 if (stack->prev == NULL) /* cannot drop below base */
1242 return &stack->tokenstate[0];
1243 return &stack->prev->tokenstate[LEVELS_PER_BLOCK - 1];
1244 }
1245
1246 static inline VSS *
1247 bump_state_level(VSS *stack)
1248 {
1249 struct tokenstate *os, *ts;
1250
1251 os = currentstate(stack);
1252
1253 if (++stack->cur >= LEVELS_PER_BLOCK) {
1254 VSS *ss;
1255
1256 ss = (VSS *)ckmalloc(sizeof (struct statestack));
1257 ss->cur = 0;
1258 ss->prev = stack;
1259 stack = ss;
1260 }
1261
1262 ts = currentstate(stack);
1263
1264 ts->ts_parenlevel = 0; /* parens inside never match outside */
1265
1266 ts->ts_quoted = os->ts_quoted & QF; /* these are default settings */
1267 ts->ts_varnest = os->ts_varnest;
1268 ts->ts_arinest = os->ts_arinest; /* when appropriate */
1269 ts->ts_syntax = os->ts_syntax; /* they will be altered */
1270
1271 return stack;
1272 }
1273
1274 static inline VSS *
1275 drop_state_level(VSS *stack)
1276 {
1277 if (stack->cur == 0) {
1278 VSS *ss;
1279
1280 ss = stack;
1281 stack = ss->prev;
1282 if (stack == NULL)
1283 return ss;
1284 ckfree(ss);
1285 }
1286 --stack->cur;
1287 return stack;
1288 }
1289
1290 static inline void
1291 cleanup_state_stack(VSS *stack)
1292 {
1293 while (stack->prev != NULL) {
1294 stack->cur = 0;
1295 stack = drop_state_level(stack);
1296 }
1297 }
1298
1299 #define PARSESUB() {goto parsesub; parsesub_return:;}
1300 #define PARSEARITH() {goto parsearith; parsearith_return:;}
1301
1302 /*
1303 * The following macros all assume the existance of a local var "stack"
1304 * which contains a pointer to the current struct stackstate
1305 */
1306
1307 /*
1308 * These are macros rather than inline funcs to avoid code churn as much
1309 * as possible - they replace macros of the same name used previously.
1310 */
1311 #define ISDBLQUOTE() (currentstate(stack)->ts_quoted & QS)
1312 #define SETDBLQUOTE() (currentstate(stack)->ts_quoted = QS | DQ)
1313 #define CLRDBLQUOTE() (currentstate(stack)->ts_quoted = \
1314 stack->cur != 0 || stack->prev ? \
1315 prevstate(stack)->ts_quoted & QF : 0)
1316
1317 /*
1318 * This set are just to avoid excess typing and line lengths...
1319 * The ones that "look like" var names must be implemented to be lvalues
1320 */
1321 #define syntax (currentstate(stack)->ts_syntax)
1322 #define parenlevel (currentstate(stack)->ts_parenlevel)
1323 #define varnest (currentstate(stack)->ts_varnest)
1324 #define arinest (currentstate(stack)->ts_arinest)
1325 #define quoted (currentstate(stack)->ts_quoted)
1326 #define TS_PUSH() (stack = bump_state_level(stack))
1327 #define TS_POP() (stack = drop_state_level(stack))
1328
1329 /*
1330 * Called to parse command substitutions. oldstyle is true if the command
1331 * is enclosed inside `` (otherwise it was enclosed in "$( )")
1332 *
1333 * Internally nlpp is a pointer to the head of the linked
1334 * list of commands (passed by reference), and savelen is the number of
1335 * characters on the top of the stack which must be preserved.
1336 */
1337 static char *
1338 parsebackq(VSS *const stack, char * const in,
1339 struct nodelist **const pbqlist, const int oldstyle, const int magicq)
1340 {
1341 struct nodelist **nlpp;
1342 const int savepbq = parsebackquote;
1343 union node *n;
1344 char *out;
1345 char *str = NULL;
1346 char *volatile sstr = str;
1347 struct jmploc jmploc;
1348 struct jmploc *const savehandler = handler;
1349 const int savelen = in - stackblock();
1350 int saveprompt;
1351 int lno;
1352
1353 if (setjmp(jmploc.loc)) {
1354 if (sstr)
1355 ckfree(__UNVOLATILE(sstr));
1356 cleanup_state_stack(stack);
1357 parsebackquote = 0;
1358 handler = savehandler;
1359 longjmp(handler->loc, 1);
1360 }
1361 INTOFF;
1362 sstr = str = NULL;
1363 if (savelen > 0) {
1364 sstr = str = ckmalloc(savelen);
1365 memcpy(str, stackblock(), savelen);
1366 }
1367 handler = &jmploc;
1368 INTON;
1369 if (oldstyle) {
1370 /*
1371 * We must read until the closing backquote, giving special
1372 * treatment to some slashes, and then push the string and
1373 * reread it as input, interpreting it normally.
1374 */
1375 int pc;
1376 int psavelen;
1377 char *pstr;
1378 int line1 = plinno;
1379
1380 VTRACE(DBG_PARSE, ("parsebackq: repackaging `` as $( )"));
1381 /*
1382 * Because the entire `...` is read here, we don't
1383 * need to bother the state stack. That will be used
1384 * (as appropriate) when the processed string is re-read.
1385 */
1386 STARTSTACKSTR(out);
1387 #ifdef DEBUG
1388 for (psavelen = 0;;psavelen++) {
1389 #else
1390 for (;;) {
1391 #endif
1392 if (needprompt) {
1393 setprompt(2);
1394 needprompt = 0;
1395 }
1396 pc = pgetc();
1397 if (pc == '`')
1398 break;
1399 switch (pc) {
1400 case '\\':
1401 pc = pgetc();
1402 #ifdef DEBUG
1403 psavelen++;
1404 #endif
1405 if (pc == '\n') { /* keep \ \n for later */
1406 plinno++;
1407 needprompt = doprompt;
1408 }
1409 if (pc != '\\' && pc != '`' && pc != '$'
1410 && (!ISDBLQUOTE() || pc != '"'))
1411 STPUTC('\\', out);
1412 break;
1413
1414 case '\n':
1415 plinno++;
1416 needprompt = doprompt;
1417 break;
1418
1419 case PEOF:
1420 startlinno = line1;
1421 synerror("EOF in backquote substitution");
1422 break;
1423
1424 default:
1425 break;
1426 }
1427 STPUTC(pc, out);
1428 }
1429 STPUTC('\0', out);
1430 VTRACE(DBG_PARSE, (" read %d", psavelen));
1431 psavelen = out - stackblock();
1432 VTRACE(DBG_PARSE, (" produced %d\n", psavelen));
1433 if (psavelen > 0) {
1434 pstr = grabstackstr(out);
1435 setinputstring(pstr, 1, line1);
1436 }
1437 }
1438 nlpp = pbqlist;
1439 while (*nlpp)
1440 nlpp = &(*nlpp)->next;
1441 *nlpp = stalloc(sizeof(struct nodelist));
1442 (*nlpp)->next = NULL;
1443 parsebackquote = oldstyle;
1444
1445 if (oldstyle) {
1446 saveprompt = doprompt;
1447 doprompt = 0;
1448 } else
1449 saveprompt = 0;
1450
1451 lno = -plinno;
1452 n = list(0);
1453 lno += plinno;
1454
1455 if (oldstyle) {
1456 if (peektoken() != TEOF)
1457 synexpect(-1, 0);
1458 doprompt = saveprompt;
1459 } else
1460 consumetoken(TRP);
1461
1462 (*nlpp)->n = n;
1463 if (oldstyle) {
1464 /*
1465 * Start reading from old file again, ignoring any pushed back
1466 * tokens left from the backquote parsing
1467 */
1468 popfile();
1469 tokpushback = 0;
1470 }
1471
1472 while (stackblocksize() <= savelen)
1473 growstackblock();
1474 STARTSTACKSTR(out);
1475 if (str) {
1476 memcpy(out, str, savelen);
1477 STADJUST(savelen, out);
1478 INTOFF;
1479 ckfree(str);
1480 sstr = str = NULL;
1481 INTON;
1482 }
1483 parsebackquote = savepbq;
1484 handler = savehandler;
1485 if (arinest || ISDBLQUOTE()) {
1486 STPUTC(CTLBACKQ | CTLQUOTE, out);
1487 while (--lno >= 0)
1488 STPUTC(CTLNONL, out);
1489 } else
1490 STPUTC(CTLBACKQ, out);
1491
1492 return out;
1493 }
1494
1495 /*
1496 * Parse a redirection operator. The parameter "out" points to a string
1497 * specifying the fd to be redirected. It is guaranteed to be either ""
1498 * or a numeric string (for now anyway). The parameter "c" contains the
1499 * first character of the redirection operator.
1500 *
1501 * Note the string "out" is on the stack, which we are about to clobber,
1502 * so process it first...
1503 */
1504
1505 static void
1506 parseredir(const char *out, int c)
1507 {
1508 union node *np;
1509 int fd;
1510
1511 fd = (*out == '\0') ? -1 : number(out);
1512
1513 np = stalloc(sizeof(struct nfile));
1514 if (c == '>') {
1515 if (fd < 0)
1516 fd = 1;
1517 c = pgetc_linecont();
1518 if (c == '>')
1519 np->type = NAPPEND;
1520 else if (c == '|')
1521 np->type = NCLOBBER;
1522 else if (c == '&')
1523 np->type = NTOFD;
1524 else {
1525 np->type = NTO;
1526 pungetc();
1527 }
1528 } else { /* c == '<' */
1529 if (fd < 0)
1530 fd = 0;
1531 switch (c = pgetc_linecont()) {
1532 case '<':
1533 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1534 np = stalloc(sizeof(struct nhere));
1535 np->nfile.fd = 0;
1536 }
1537 np->type = NHERE;
1538 heredoc = stalloc(sizeof(struct HereDoc));
1539 heredoc->here = np;
1540 heredoc->startline = plinno;
1541 if ((c = pgetc_linecont()) == '-') {
1542 heredoc->striptabs = 1;
1543 } else {
1544 heredoc->striptabs = 0;
1545 pungetc();
1546 }
1547 break;
1548
1549 case '&':
1550 np->type = NFROMFD;
1551 break;
1552
1553 case '>':
1554 np->type = NFROMTO;
1555 break;
1556
1557 default:
1558 np->type = NFROM;
1559 pungetc();
1560 break;
1561 }
1562 }
1563 np->nfile.fd = fd;
1564
1565 redirnode = np; /* this is the "value" of TRENODE */
1566 }
1567
1568 /*
1569 * Called to parse a backslash escape sequence inside $'...'.
1570 * The backslash has already been read.
1571 */
1572 static char *
1573 readcstyleesc(char *out)
1574 {
1575 int c, vc, i, n;
1576 unsigned int v;
1577
1578 c = pgetc();
1579 switch (c) {
1580 case '\0':
1581 case PEOF:
1582 synerror("Unterminated quoted string");
1583 case '\n':
1584 plinno++;
1585 if (doprompt)
1586 setprompt(2);
1587 else
1588 setprompt(0);
1589 return out;
1590
1591 case '\\':
1592 case '\'':
1593 case '"':
1594 v = c;
1595 break;
1596
1597 case 'a': v = '\a'; break;
1598 case 'b': v = '\b'; break;
1599 case 'e': v = '\033'; break;
1600 case 'f': v = '\f'; break;
1601 case 'n': v = '\n'; break;
1602 case 'r': v = '\r'; break;
1603 case 't': v = '\t'; break;
1604 case 'v': v = '\v'; break;
1605
1606 case '0': case '1': case '2': case '3':
1607 case '4': case '5': case '6': case '7':
1608 v = c - '0';
1609 c = pgetc();
1610 if (c >= '0' && c <= '7') {
1611 v <<= 3;
1612 v += c - '0';
1613 c = pgetc();
1614 if (c >= '0' && c <= '7') {
1615 v <<= 3;
1616 v += c - '0';
1617 } else
1618 pungetc();
1619 } else
1620 pungetc();
1621 break;
1622
1623 case 'c':
1624 c = pgetc();
1625 if (c < 0x3f || c > 0x7a || c == 0x60)
1626 synerror("Bad \\c escape sequence");
1627 if (c == '\\' && pgetc() != '\\')
1628 synerror("Bad \\c\\ escape sequence");
1629 if (c == '?')
1630 v = 127;
1631 else
1632 v = c & 0x1f;
1633 break;
1634
1635 case 'x':
1636 n = 2;
1637 goto hexval;
1638 case 'u':
1639 n = 4;
1640 goto hexval;
1641 case 'U':
1642 n = 8;
1643 hexval:
1644 v = 0;
1645 for (i = 0; i < n; i++) {
1646 c = pgetc();
1647 if (c >= '0' && c <= '9')
1648 v = (v << 4) + c - '0';
1649 else if (c >= 'A' && c <= 'F')
1650 v = (v << 4) + c - 'A' + 10;
1651 else if (c >= 'a' && c <= 'f')
1652 v = (v << 4) + c - 'a' + 10;
1653 else {
1654 pungetc();
1655 break;
1656 }
1657 }
1658 if (n > 2 && v > 127) {
1659 if (v >= 0xd800 && v <= 0xdfff)
1660 synerror("Invalid \\u escape sequence");
1661
1662 /* XXX should we use iconv here. What locale? */
1663 CHECKSTRSPACE(4, out);
1664
1665 if (v <= 0x7ff) {
1666 USTPUTC(0xc0 | v >> 6, out);
1667 USTPUTC(0x80 | (v & 0x3f), out);
1668 return out;
1669 } else if (v <= 0xffff) {
1670 USTPUTC(0xe0 | v >> 12, out);
1671 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1672 USTPUTC(0x80 | (v & 0x3f), out);
1673 return out;
1674 } else if (v <= 0x10ffff) {
1675 USTPUTC(0xf0 | v >> 18, out);
1676 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1677 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1678 USTPUTC(0x80 | (v & 0x3f), out);
1679 return out;
1680 }
1681 if (v > 127)
1682 v = '?';
1683 }
1684 break;
1685 default:
1686 synerror("Unknown $'' escape sequence");
1687 }
1688 vc = (char)v;
1689
1690 /*
1691 * If we managed to create a \n from a \ sequence (no matter how)
1692 * then we replace it with the magic CRTCNL control char, which
1693 * will turn into a \n again later, but in the meantime, never
1694 * causes LINENO increments.
1695 */
1696 if (vc == '\n') {
1697 USTPUTC(CTLCNL, out);
1698 return out;
1699 }
1700
1701 /*
1702 * We can't handle NUL bytes.
1703 * POSIX says we should skip till the closing quote.
1704 */
1705 if (vc == '\0') {
1706 while ((c = pgetc()) != '\'') {
1707 if (c == '\\')
1708 c = pgetc();
1709 if (c == PEOF)
1710 synerror("Unterminated quoted string");
1711 if (c == '\n') {
1712 plinno++;
1713 if (doprompt)
1714 setprompt(2);
1715 else
1716 setprompt(0);
1717 }
1718 }
1719 pungetc();
1720 return out;
1721 }
1722 if (NEEDESC(vc))
1723 USTPUTC(CTLESC, out);
1724 USTPUTC(vc, out);
1725 return out;
1726 }
1727
1728 /*
1729 * The lowest level basic tokenizer.
1730 *
1731 * The next input byte (character) is in firstc, syn says which
1732 * syntax tables we are to use (basic, single or double quoted, or arith)
1733 * and magicq (used with sqsyntax and dqsyntax only) indicates that the
1734 * quote character itself is not special (used parsing here docs and similar)
1735 *
1736 * The result is the type of the next token (its value, when there is one,
1737 * is saved in the relevant global var - must fix that someday!) which is
1738 * also saved for re-reading ("lasttoken").
1739 *
1740 * Overall, this routine does far more parsing than it is supposed to.
1741 * That will also need fixing, someday...
1742 */
1743 STATIC int
1744 readtoken1(int firstc, char const *syn, int magicq)
1745 {
1746 int c;
1747 char * out;
1748 int len;
1749 struct nodelist *bqlist;
1750 int quotef;
1751 VSS static_stack;
1752 VSS *stack = &static_stack;
1753
1754 stack->prev = NULL;
1755 stack->cur = 0;
1756
1757 syntax = syn;
1758
1759 startlinno = plinno;
1760 varnest = 0;
1761 quoted = 0;
1762 if (syntax == DQSYNTAX)
1763 SETDBLQUOTE();
1764 quotef = 0;
1765 bqlist = NULL;
1766 arinest = 0;
1767 parenlevel = 0;
1768 elided_nl = 0;
1769
1770 STARTSTACKSTR(out);
1771
1772 for (c = firstc ;; c = pgetc_macro()) { /* until of token */
1773 if (syntax == ARISYNTAX)
1774 out = insert_elided_nl(out);
1775 CHECKSTRSPACE(6, out); /* permit 6 calls to USTPUTC */
1776 switch (syntax[c]) {
1777 case CNL: /* '\n' */
1778 if (syntax == BASESYNTAX && varnest == 0)
1779 break; /* exit loop */
1780 USTPUTC(c, out);
1781 plinno++;
1782 if (doprompt)
1783 setprompt(2);
1784 else
1785 setprompt(0);
1786 continue;
1787
1788 case CSBACK: /* single quoted backslash */
1789 if ((quoted & QF) == CQ) {
1790 out = readcstyleesc(out);
1791 continue;
1792 }
1793 USTPUTC(CTLESC, out);
1794 /* FALLTHROUGH */
1795 case CWORD:
1796 USTPUTC(c, out);
1797 continue;
1798
1799 case CCTL:
1800 if (!magicq || ISDBLQUOTE())
1801 USTPUTC(CTLESC, out);
1802 USTPUTC(c, out);
1803 continue;
1804 case CBACK: /* backslash */
1805 c = pgetc();
1806 if (c == PEOF) {
1807 USTPUTC('\\', out);
1808 pungetc();
1809 continue;
1810 }
1811 if (c == '\n') {
1812 plinno++;
1813 elided_nl++;
1814 if (doprompt)
1815 setprompt(2);
1816 else
1817 setprompt(0);
1818 continue;
1819 }
1820 quotef = 1; /* current token is quoted */
1821 if (ISDBLQUOTE() && c != '\\' && c != '`' &&
1822 c != '$' && (c != '"' || magicq)) {
1823 /*
1824 * retain the \ (which we *know* needs CTLESC)
1825 * when in "..." and the following char is
1826 * not one of the magic few.)
1827 * Otherwise the \ has done its work, and
1828 * is dropped.
1829 */
1830 USTPUTC(CTLESC, out);
1831 USTPUTC('\\', out);
1832 }
1833 if (NEEDESC(c))
1834 USTPUTC(CTLESC, out);
1835 else if (!magicq) {
1836 USTPUTC(CTLQUOTEMARK, out);
1837 USTPUTC(c, out);
1838 if (varnest != 0)
1839 USTPUTC(CTLQUOTEEND, out);
1840 continue;
1841 }
1842 USTPUTC(c, out);
1843 continue;
1844 case CSQUOTE:
1845 if (syntax != SQSYNTAX) {
1846 if (!magicq)
1847 USTPUTC(CTLQUOTEMARK, out);
1848 quotef = 1;
1849 TS_PUSH();
1850 syntax = SQSYNTAX;
1851 quoted = SQ;
1852 continue;
1853 }
1854 if (magicq && arinest == 0 && varnest == 0) {
1855 /* Ignore inside quoted here document */
1856 USTPUTC(c, out);
1857 continue;
1858 }
1859 /* End of single quotes... */
1860 TS_POP();
1861 if (syntax == BASESYNTAX && varnest != 0)
1862 USTPUTC(CTLQUOTEEND, out);
1863 continue;
1864 case CDQUOTE:
1865 if (magicq && arinest == 0 && varnest == 0) {
1866 /* Ignore inside here document */
1867 USTPUTC(c, out);
1868 continue;
1869 }
1870 quotef = 1;
1871 if (arinest) {
1872 if (ISDBLQUOTE()) {
1873 TS_POP();
1874 } else {
1875 TS_PUSH();
1876 syntax = DQSYNTAX;
1877 SETDBLQUOTE();
1878 USTPUTC(CTLQUOTEMARK, out);
1879 }
1880 continue;
1881 }
1882 if (magicq)
1883 continue;
1884 if (ISDBLQUOTE()) {
1885 TS_POP();
1886 if (varnest != 0)
1887 USTPUTC(CTLQUOTEEND, out);
1888 } else {
1889 TS_PUSH();
1890 syntax = DQSYNTAX;
1891 SETDBLQUOTE();
1892 USTPUTC(CTLQUOTEMARK, out);
1893 }
1894 continue;
1895 case CVAR: /* '$' */
1896 out = insert_elided_nl(out);
1897 PARSESUB(); /* parse substitution */
1898 continue;
1899 case CENDVAR: /* CLOSEBRACE */
1900 if (varnest > 0 && !ISDBLQUOTE()) {
1901 TS_POP();
1902 USTPUTC(CTLENDVAR, out);
1903 } else {
1904 USTPUTC(c, out);
1905 }
1906 out = insert_elided_nl(out);
1907 continue;
1908 case CLP: /* '(' in arithmetic */
1909 parenlevel++;
1910 USTPUTC(c, out);
1911 continue;;
1912 case CRP: /* ')' in arithmetic */
1913 if (parenlevel > 0) {
1914 USTPUTC(c, out);
1915 --parenlevel;
1916 } else {
1917 if (pgetc_linecont() == /*(*/ ')') {
1918 out = insert_elided_nl(out);
1919 if (--arinest == 0) {
1920 TS_POP();
1921 USTPUTC(CTLENDARI, out);
1922 } else
1923 USTPUTC(/*(*/ ')', out);
1924 } else {
1925 break; /* to synerror() just below */
1926 #if 0 /* the old way, causes weird errors on bad input */
1927 /*
1928 * unbalanced parens
1929 * (don't 2nd guess - no error)
1930 */
1931 pungetc();
1932 USTPUTC(/*(*/ ')', out);
1933 #endif
1934 }
1935 }
1936 continue;
1937 case CBQUOTE: /* '`' */
1938 out = parsebackq(stack, out, &bqlist, 1, magicq);
1939 continue;
1940 case CEOF: /* --> c == PEOF */
1941 break; /* will exit loop */
1942 default:
1943 if (varnest == 0 && !ISDBLQUOTE())
1944 break; /* exit loop */
1945 USTPUTC(c, out);
1946 continue;
1947 }
1948 break; /* break from switch -> break from for loop too */
1949 }
1950
1951 if (syntax == ARISYNTAX) {
1952 cleanup_state_stack(stack);
1953 synerror(/*((*/ "Missing '))'");
1954 }
1955 if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
1956 cleanup_state_stack(stack);
1957 synerror("Unterminated quoted string");
1958 }
1959 if (varnest != 0) {
1960 cleanup_state_stack(stack);
1961 startlinno = plinno;
1962 /* { */
1963 synerror("Missing '}'");
1964 }
1965
1966 STPUTC('\0', out);
1967 len = out - stackblock();
1968 out = stackblock();
1969
1970 if (!magicq) {
1971 if ((c == '<' || c == '>')
1972 && quotef == 0 && (*out == '\0' || is_number(out))) {
1973 parseredir(out, c);
1974 cleanup_state_stack(stack);
1975 return lasttoken = TREDIR;
1976 } else {
1977 pungetc();
1978 }
1979 }
1980
1981 VTRACE(DBG_PARSE,
1982 ("readtoken1 %sword \"%s\", completed%s (%d) left %d enl\n",
1983 (quotef ? "quoted " : ""), out, (bqlist ? " with cmdsubs" : ""),
1984 len, elided_nl));
1985
1986 quoteflag = quotef;
1987 backquotelist = bqlist;
1988 grabstackblock(len);
1989 wordtext = out;
1990 cleanup_state_stack(stack);
1991 return lasttoken = TWORD;
1992 /* end of readtoken routine */
1993
1994
1995 /*
1996 * Parse a substitution. At this point, we have read the dollar sign
1997 * and nothing else.
1998 */
1999
2000 parsesub: {
2001 int subtype;
2002 int typeloc;
2003 int flags;
2004 char *p;
2005 static const char types[] = "}-+?=";
2006
2007 c = pgetc_linecont();
2008 if (c == '(' /*)*/) { /* $(command) or $((arith)) */
2009 if (pgetc_linecont() == '(' /*')'*/ ) {
2010 out = insert_elided_nl(out);
2011 PARSEARITH();
2012 } else {
2013 out = insert_elided_nl(out);
2014 pungetc();
2015 out = parsebackq(stack, out, &bqlist, 0, magicq);
2016 }
2017 } else if (c == OPENBRACE || is_name(c) || is_special(c)) {
2018 USTPUTC(CTLVAR, out);
2019 typeloc = out - stackblock();
2020 USTPUTC(VSNORMAL, out);
2021 subtype = VSNORMAL;
2022 flags = 0;
2023 if (c == OPENBRACE) {
2024 c = pgetc_linecont();
2025 if (c == '#') {
2026 if ((c = pgetc_linecont()) == CLOSEBRACE)
2027 c = '#';
2028 else if (is_name(c) || isdigit(c))
2029 subtype = VSLENGTH;
2030 else if (is_special(c)) {
2031 /*
2032 * ${#} is $# - the number of sh params
2033 * ${##} is the length of ${#}
2034 * ${###} is ${#} with as much nothing
2035 * as possible removed from start
2036 * ${##1} is ${#} with leading 1 gone
2037 * ${##\#} is ${#} with leading # gone
2038 *
2039 * this stuff is UGLY!
2040 */
2041 if (pgetc_linecont() == CLOSEBRACE) {
2042 pungetc();
2043 subtype = VSLENGTH;
2044 } else {
2045 static char cbuf[2];
2046
2047 pungetc(); /* would like 2 */
2048 cbuf[0] = c; /* so ... */
2049 cbuf[1] = '\0';
2050 pushstring(cbuf, 1, NULL);
2051 c = '#'; /* ${#:...} */
2052 subtype = 0; /* .. or similar */
2053 }
2054 } else {
2055 pungetc();
2056 c = '#';
2057 subtype = 0;
2058 }
2059 }
2060 else
2061 subtype = 0;
2062 }
2063 if (is_name(c)) {
2064 p = out;
2065 do {
2066 STPUTC(c, out);
2067 c = pgetc_linecont();
2068 } while (is_in_name(c));
2069 #if 0
2070 if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
2071 int i;
2072 int linno;
2073 char buf[10];
2074
2075 /*
2076 * The "LINENO hack"
2077 *
2078 * Replace the variable name with the
2079 * current line number.
2080 */
2081 linno = plinno;
2082 if (funclinno != 0)
2083 linno -= funclinno - 1;
2084 snprintf(buf, sizeof(buf), "%d", linno);
2085 STADJUST(-6, out);
2086 for (i = 0; buf[i] != '\0'; i++)
2087 STPUTC(buf[i], out);
2088 flags |= VSLINENO;
2089 }
2090 #endif
2091 } else if (is_digit(c)) {
2092 do {
2093 STPUTC(c, out);
2094 c = pgetc_linecont();
2095 } while (subtype != VSNORMAL && is_digit(c));
2096 }
2097 else if (is_special(c)) {
2098 USTPUTC(c, out);
2099 c = pgetc_linecont();
2100 }
2101 else {
2102 badsub:
2103 cleanup_state_stack(stack);
2104 synerror("Bad substitution");
2105 }
2106
2107 STPUTC('=', out);
2108 if (subtype == 0) {
2109 switch (c) {
2110 case ':':
2111 flags |= VSNUL;
2112 c = pgetc_linecont();
2113 /*FALLTHROUGH*/
2114 default:
2115 p = strchr(types, c);
2116 if (p == NULL)
2117 goto badsub;
2118 subtype = p - types + VSNORMAL;
2119 break;
2120 case '%':
2121 case '#':
2122 {
2123 int cc = c;
2124 subtype = c == '#' ? VSTRIMLEFT :
2125 VSTRIMRIGHT;
2126 c = pgetc_linecont();
2127 if (c == cc)
2128 subtype++;
2129 else
2130 pungetc();
2131 break;
2132 }
2133 }
2134 } else {
2135 if (subtype == VSLENGTH && c != /*{*/ '}')
2136 synerror("no modifiers allowed with ${#var}");
2137 pungetc();
2138 }
2139 if (ISDBLQUOTE() || arinest)
2140 flags |= VSQUOTE;
2141 if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
2142 flags |= VSPATQ;
2143 *(stackblock() + typeloc) = subtype | flags;
2144 if (subtype != VSNORMAL) {
2145 TS_PUSH();
2146 varnest++;
2147 arinest = 0;
2148 if (subtype > VSASSIGN) { /* # ## % %% */
2149 syntax = BASESYNTAX;
2150 CLRDBLQUOTE();
2151 }
2152 }
2153 } else if (c == '\'' && syntax == BASESYNTAX) {
2154 USTPUTC(CTLQUOTEMARK, out);
2155 quotef = 1;
2156 TS_PUSH();
2157 syntax = SQSYNTAX;
2158 quoted = CQ;
2159 } else {
2160 USTPUTC('$', out);
2161 pungetc();
2162 }
2163 goto parsesub_return;
2164 }
2165
2166
2167 /*
2168 * Parse an arithmetic expansion (indicate start of one and set state)
2169 */
2170 parsearith: {
2171
2172 #if 0
2173 if (syntax == ARISYNTAX) {
2174 /*
2175 * we collapse embedded arithmetic expansion to
2176 * parentheses, which should be equivalent
2177 *
2178 * XXX It isn't, must fix, soonish...
2179 */
2180 USTPUTC('(' /*)*/, out);
2181 USTPUTC('(' /*)*/, out);
2182 /*
2183 * Need 2 of them because there will (should be)
2184 * two closing ))'s to follow later.
2185 */
2186 parenlevel += 2;
2187 } else
2188 #endif
2189 {
2190 USTPUTC(CTLARI, out);
2191 if (ISDBLQUOTE())
2192 USTPUTC('"',out);
2193 else
2194 USTPUTC(' ',out);
2195
2196 TS_PUSH();
2197 syntax = ARISYNTAX;
2198 arinest = 1;
2199 varnest = 0;
2200 }
2201 goto parsearith_return;
2202 }
2203
2204 } /* end of readtoken */
2205
2206
2207
2208
2209 #ifdef mkinit
2210 INCLUDE "parser.h"
2211
2212 RESET {
2213 psp.v_current_parser = &parse_state;
2214
2215 parse_state.ps_tokpushback = 0;
2216 parse_state.ps_checkkwd = 0;
2217 parse_state.ps_heredoclist = NULL;
2218 }
2219 #endif
2220
2221 /*
2222 * Returns true if the text contains nothing to expand (no dollar signs
2223 * or backquotes).
2224 */
2225
2226 STATIC int
2227 noexpand(char *text)
2228 {
2229 char *p;
2230 char c;
2231
2232 p = text;
2233 while ((c = *p++) != '\0') {
2234 if (c == CTLQUOTEMARK)
2235 continue;
2236 if (c == CTLESC)
2237 p++;
2238 else if (BASESYNTAX[(int)c] == CCTL)
2239 return 0;
2240 }
2241 return 1;
2242 }
2243
2244
2245 /*
2246 * Return true if the argument is a legal variable name (a letter or
2247 * underscore followed by zero or more letters, underscores, and digits).
2248 */
2249
2250 int
2251 goodname(const char *name)
2252 {
2253 const char *p;
2254
2255 p = name;
2256 if (! is_name(*p))
2257 return 0;
2258 while (*++p) {
2259 if (! is_in_name(*p))
2260 return 0;
2261 }
2262 return 1;
2263 }
2264
2265 /*
2266 * skip past any \n's, and leave lasttoken set to whatever follows
2267 */
2268 STATIC void
2269 linebreak(void)
2270 {
2271 while (readtoken() == TNL)
2272 ;
2273 }
2274
2275 /*
2276 * The next token must be "token" -- check, then move past it
2277 */
2278 STATIC void
2279 consumetoken(int token)
2280 {
2281 if (readtoken() != token) {
2282 VTRACE(DBG_PARSE, ("consumetoken(%d): expecting %s got %s",
2283 token, tokname[token], tokname[lasttoken]));
2284 CVTRACE(DBG_PARSE, (lasttoken==TWORD), (" \"%s\"", wordtext));
2285 VTRACE(DBG_PARSE, ("\n"));
2286 synexpect(token, NULL);
2287 }
2288 }
2289
2290 /*
2291 * Called when an unexpected token is read during the parse. The argument
2292 * is the token that is expected, or -1 if more than one type of token can
2293 * occur at this point.
2294 */
2295
2296 STATIC void
2297 synexpect(int token, const char *text)
2298 {
2299 char msg[64];
2300 char *p;
2301
2302 if (lasttoken == TWORD) {
2303 size_t len = strlen(wordtext);
2304
2305 if (len <= 13)
2306 fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
2307 else
2308 fmtstr(msg, 34,
2309 "Word \"%.10s...\" unexpected", wordtext);
2310 } else
2311 fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
2312
2313 p = strchr(msg, '\0');
2314 if (text)
2315 fmtstr(p, 30, " (expecting \"%.10s\")", text);
2316 else if (token >= 0)
2317 fmtstr(p, 30, " (expecting %s)", tokname[token]);
2318
2319 synerror(msg);
2320 /* NOTREACHED */
2321 }
2322
2323
2324 STATIC void
2325 synerror(const char *msg)
2326 {
2327 error("%d: Syntax error: %s", startlinno, msg);
2328 /* NOTREACHED */
2329 }
2330
2331 STATIC void
2332 setprompt(int which)
2333 {
2334 whichprompt = which;
2335
2336 #ifndef SMALL
2337 if (!el)
2338 #endif
2339 out2str(getprompt(NULL));
2340 }
2341
2342 /*
2343 * handle getting the next character, while ignoring \ \n
2344 * (which is a little tricky as we only have one char of pushback
2345 * and we need that one elsewhere).
2346 */
2347 STATIC int
2348 pgetc_linecont(void)
2349 {
2350 int c;
2351
2352 while ((c = pgetc_macro()) == '\\') {
2353 c = pgetc();
2354 if (c == '\n') {
2355 plinno++;
2356 elided_nl++;
2357 if (doprompt)
2358 setprompt(2);
2359 else
2360 setprompt(0);
2361 } else {
2362 pungetc();
2363 /* Allow the backslash to be pushed back. */
2364 pushstring("\\", 1, NULL);
2365 return (pgetc());
2366 }
2367 }
2368 return (c);
2369 }
2370
2371 /*
2372 * called by editline -- any expansions to the prompt
2373 * should be added here.
2374 */
2375 const char *
2376 getprompt(void *unused)
2377 {
2378 char *p;
2379 const char *cp;
2380 int wp;
2381
2382 if (!doprompt)
2383 return "";
2384
2385 VTRACE(DBG_PARSE|DBG_EXPAND, ("getprompt %d\n", whichprompt));
2386
2387 switch (wp = whichprompt) {
2388 case 0:
2389 return "";
2390 case 1:
2391 p = ps1val();
2392 break;
2393 case 2:
2394 p = ps2val();
2395 break;
2396 default:
2397 return "<internal prompt error>";
2398 }
2399 if (p == NULL)
2400 return "";
2401
2402 VTRACE(DBG_PARSE|DBG_EXPAND, ("prompt <<%s>>\n", p));
2403
2404 cp = expandstr(p, plinno);
2405 whichprompt = wp; /* history depends on it not changing */
2406
2407 VTRACE(DBG_PARSE|DBG_EXPAND, ("prompt -> <<%s>>\n", cp));
2408
2409 return cp;
2410 }
2411
2412 /*
2413 * Expand a string ... used for expanding prompts (PS1...)
2414 *
2415 * Never return NULL, always some string (return input string if invalid)
2416 *
2417 * The internal routine does the work, leaving the result on the
2418 * stack (or in a static string, or even the input string) and
2419 * handles parser recursion, and cleanup after an error while parsing.
2420 *
2421 * The visible interface copies the result off the stack (if it is there),
2422 * and handles stack management, leaving the stack in the exact same
2423 * state it was when expandstr() was called (so it can be used part way
2424 * through building a stack data structure - as in when PS2 is being
2425 * expanded half way through reading a "command line")
2426 *
2427 * on error, expandonstack() cleans up the parser state, but then
2428 * simply jumps out through expandstr() withut doing any stack cleanup,
2429 * which is OK, as the error handler must deal with that anyway.
2430 *
2431 * The split into two funcs is to avoid problems with setjmp/longjmp
2432 * and local variables which could otherwise be optimised into bizarre
2433 * behaviour.
2434 */
2435 static const char *
2436 expandonstack(char *ps, int lineno)
2437 {
2438 union node n;
2439 struct jmploc jmploc;
2440 struct jmploc *const savehandler = handler;
2441 struct parsefile *const savetopfile = getcurrentfile();
2442 const int save_x = xflag;
2443 struct parse_state new_state = init_parse_state;
2444 struct parse_state *const saveparser = psp.v_current_parser;
2445 const char *result = NULL;
2446
2447 if (!setjmp(jmploc.loc)) {
2448 handler = &jmploc;
2449
2450 psp.v_current_parser = &new_state;
2451 setinputstring(ps, 1, lineno);
2452
2453 readtoken1(pgetc(), DQSYNTAX, 1);
2454 if (backquotelist != NULL && !promptcmds)
2455 result = "-o promptcmds not set: ";
2456 else {
2457 n.narg.type = NARG;
2458 n.narg.next = NULL;
2459 n.narg.text = wordtext;
2460 n.narg.lineno = lineno;
2461 n.narg.backquote = backquotelist;
2462
2463 xflag = 0; /* we might be expanding PS4 ... */
2464 expandarg(&n, NULL, 0);
2465 result = stackblock();
2466 }
2467 INTOFF;
2468 }
2469 psp.v_current_parser = saveparser;
2470 xflag = save_x;
2471 popfilesupto(savetopfile);
2472 handler = savehandler;
2473
2474 if (exception == EXEXIT)
2475 longjmp(handler->loc, 1);
2476
2477 if (result != NULL) {
2478 INTON;
2479 } else {
2480 if (exception == EXINT)
2481 exraise(SIGINT);
2482 result = ps;
2483 }
2484
2485 return result;
2486 }
2487
2488 const char *
2489 expandstr(char *ps, int lineno)
2490 {
2491 const char *result = NULL;
2492 struct stackmark smark;
2493 static char *buffer = NULL; /* storage for prompt, never freed */
2494 static size_t bufferlen = 0;
2495
2496 setstackmark(&smark);
2497 /*
2498 * At this point we anticipate that there may be a string
2499 * growing on the stack, but we have no idea how big it is.
2500 * However we know that it cannot be bigger than the current
2501 * allocated stack block, so simply reserve the whole thing,
2502 * then we can use the stack without barfing all over what
2503 * is there already... (the stack mark undoes this later.)
2504 */
2505 (void) stalloc(stackblocksize());
2506
2507 result = expandonstack(ps, lineno);
2508
2509 if (__predict_true(result == stackblock())) {
2510 size_t len = strlen(result) + 1;
2511
2512 /*
2513 * the result (usual case) is on the stack, which we
2514 * are just about to discard (popstackmark()) so we
2515 * need to move it somewhere safe first.
2516 */
2517
2518 if (__predict_false(len > bufferlen)) {
2519 char *new;
2520 size_t newlen = bufferlen;
2521
2522 if (__predict_false(len > (SIZE_MAX >> 4))) {
2523 result = "huge prompt: ";
2524 goto getout;
2525 }
2526
2527 if (newlen == 0)
2528 newlen = 32;
2529 while (newlen <= len)
2530 newlen <<= 1;
2531
2532 new = (char *)realloc(buffer, newlen);
2533
2534 if (__predict_false(new == NULL)) {
2535 /*
2536 * this should rarely (if ever) happen
2537 * but we must do something when it does...
2538 */
2539 result = "No mem for prompt: ";
2540 goto getout;
2541 } else {
2542 buffer = new;
2543 bufferlen = newlen;
2544 }
2545 }
2546 (void)memcpy(buffer, result, len);
2547 result = buffer;
2548 }
2549
2550 getout:;
2551 popstackmark(&smark);
2552
2553 return result;
2554 }
2555