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