parser.c revision 1.158 1 /* $NetBSD: parser.c,v 1.158 2018/12/09 17:33:38 christos 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.158 2018/12/09 17:33:38 christos 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 const int savelen = in - stackblock();
1351 int saveprompt;
1352 int lno;
1353
1354 if (setjmp(jmploc.loc)) {
1355 if (sstr)
1356 ckfree(__UNVOLATILE(sstr));
1357 cleanup_state_stack(stack);
1358 parsebackquote = 0;
1359 handler = savehandler;
1360 longjmp(handler->loc, 1);
1361 }
1362 INTOFF;
1363 sstr = str = NULL;
1364 if (savelen > 0) {
1365 sstr = str = ckmalloc(savelen);
1366 memcpy(str, stackblock(), savelen);
1367 }
1368 handler = &jmploc;
1369 INTON;
1370 if (oldstyle) {
1371 /*
1372 * We must read until the closing backquote, giving special
1373 * treatment to some slashes, and then push the string and
1374 * reread it as input, interpreting it normally.
1375 */
1376 int pc;
1377 int psavelen;
1378 char *pstr;
1379 int line1 = plinno;
1380
1381 VTRACE(DBG_PARSE, ("parsebackq: repackaging `` as $( )"));
1382 /*
1383 * Because the entire `...` is read here, we don't
1384 * need to bother the state stack. That will be used
1385 * (as appropriate) when the processed string is re-read.
1386 */
1387 STARTSTACKSTR(out);
1388 #ifdef DEBUG
1389 for (psavelen = 0;;psavelen++) {
1390 #else
1391 for (;;) {
1392 #endif
1393 if (needprompt) {
1394 setprompt(2);
1395 needprompt = 0;
1396 }
1397 pc = pgetc();
1398 if (pc == '`')
1399 break;
1400 switch (pc) {
1401 case '\\':
1402 pc = pgetc();
1403 #ifdef DEBUG
1404 psavelen++;
1405 #endif
1406 if (pc == '\n') { /* keep \ \n for later */
1407 plinno++;
1408 needprompt = doprompt;
1409 }
1410 if (pc != '\\' && pc != '`' && pc != '$'
1411 && (!ISDBLQUOTE() || pc != '"'))
1412 STPUTC('\\', out);
1413 break;
1414
1415 case '\n':
1416 plinno++;
1417 needprompt = doprompt;
1418 break;
1419
1420 case PEOF:
1421 startlinno = line1;
1422 synerror("EOF in backquote substitution");
1423 break;
1424
1425 default:
1426 break;
1427 }
1428 STPUTC(pc, out);
1429 }
1430 STPUTC('\0', out);
1431 VTRACE(DBG_PARSE, (" read %d", psavelen));
1432 psavelen = out - stackblock();
1433 VTRACE(DBG_PARSE, (" produced %d\n", psavelen));
1434 if (psavelen > 0) {
1435 pstr = grabstackstr(out);
1436 setinputstring(pstr, 1, line1);
1437 }
1438 }
1439 nlpp = pbqlist;
1440 while (*nlpp)
1441 nlpp = &(*nlpp)->next;
1442 *nlpp = stalloc(sizeof(struct nodelist));
1443 (*nlpp)->next = NULL;
1444 parsebackquote = oldstyle;
1445
1446 if (oldstyle) {
1447 saveprompt = doprompt;
1448 doprompt = 0;
1449 } else
1450 saveprompt = 0;
1451
1452 lno = -plinno;
1453 n = list(0);
1454 lno += plinno;
1455
1456 if (oldstyle) {
1457 if (peektoken() != TEOF)
1458 synexpect(-1, 0);
1459 doprompt = saveprompt;
1460 } else
1461 consumetoken(TRP);
1462
1463 (*nlpp)->n = n;
1464 if (oldstyle) {
1465 /*
1466 * Start reading from old file again, ignoring any pushed back
1467 * tokens left from the backquote parsing
1468 */
1469 popfile();
1470 tokpushback = 0;
1471 }
1472
1473 while (stackblocksize() <= savelen)
1474 growstackblock();
1475 STARTSTACKSTR(out);
1476 if (str) {
1477 memcpy(out, str, savelen);
1478 STADJUST(savelen, out);
1479 INTOFF;
1480 ckfree(str);
1481 sstr = str = NULL;
1482 INTON;
1483 }
1484 parsebackquote = savepbq;
1485 handler = savehandler;
1486 if (arinest || ISDBLQUOTE()) {
1487 STPUTC(CTLBACKQ | CTLQUOTE, out);
1488 while (--lno >= 0)
1489 STPUTC(CTLNONL, out);
1490 } else
1491 STPUTC(CTLBACKQ, out);
1492
1493 return out;
1494 }
1495
1496 /*
1497 * Parse a redirection operator. The parameter "out" points to a string
1498 * specifying the fd to be redirected. It is guaranteed to be either ""
1499 * or a numeric string (for now anyway). The parameter "c" contains the
1500 * first character of the redirection operator.
1501 *
1502 * Note the string "out" is on the stack, which we are about to clobber,
1503 * so process it first...
1504 */
1505
1506 static void
1507 parseredir(const char *out, int c)
1508 {
1509 union node *np;
1510 int fd;
1511
1512 fd = (*out == '\0') ? -1 : number(out);
1513
1514 np = stalloc(sizeof(struct nfile));
1515 if (c == '>') {
1516 if (fd < 0)
1517 fd = 1;
1518 c = pgetc_linecont();
1519 if (c == '>')
1520 np->type = NAPPEND;
1521 else if (c == '|')
1522 np->type = NCLOBBER;
1523 else if (c == '&')
1524 np->type = NTOFD;
1525 else {
1526 np->type = NTO;
1527 pungetc();
1528 }
1529 } else { /* c == '<' */
1530 if (fd < 0)
1531 fd = 0;
1532 switch (c = pgetc_linecont()) {
1533 case '<':
1534 if (sizeof (struct nfile) != sizeof (struct nhere)) {
1535 np = stalloc(sizeof(struct nhere));
1536 np->nfile.fd = 0;
1537 }
1538 np->type = NHERE;
1539 heredoc = stalloc(sizeof(struct HereDoc));
1540 heredoc->here = np;
1541 heredoc->startline = plinno;
1542 if ((c = pgetc_linecont()) == '-') {
1543 heredoc->striptabs = 1;
1544 } else {
1545 heredoc->striptabs = 0;
1546 pungetc();
1547 }
1548 break;
1549
1550 case '&':
1551 np->type = NFROMFD;
1552 break;
1553
1554 case '>':
1555 np->type = NFROMTO;
1556 break;
1557
1558 default:
1559 np->type = NFROM;
1560 pungetc();
1561 break;
1562 }
1563 }
1564 np->nfile.fd = fd;
1565
1566 redirnode = np; /* this is the "value" of TRENODE */
1567 }
1568
1569 /*
1570 * Called to parse a backslash escape sequence inside $'...'.
1571 * The backslash has already been read.
1572 */
1573 static char *
1574 readcstyleesc(char *out)
1575 {
1576 int c, vc, i, n;
1577 unsigned int v;
1578
1579 c = pgetc();
1580 switch (c) {
1581 case '\0':
1582 case PEOF:
1583 synerror("Unterminated quoted string");
1584 case '\n':
1585 plinno++;
1586 if (doprompt)
1587 setprompt(2);
1588 else
1589 setprompt(0);
1590 return out;
1591
1592 case '\\':
1593 case '\'':
1594 case '"':
1595 v = c;
1596 break;
1597
1598 case 'a': v = '\a'; break;
1599 case 'b': v = '\b'; break;
1600 case 'e': v = '\033'; break;
1601 case 'f': v = '\f'; break;
1602 case 'n': v = '\n'; break;
1603 case 'r': v = '\r'; break;
1604 case 't': v = '\t'; break;
1605 case 'v': v = '\v'; break;
1606
1607 case '0': case '1': case '2': case '3':
1608 case '4': case '5': case '6': case '7':
1609 v = c - '0';
1610 c = pgetc();
1611 if (c >= '0' && c <= '7') {
1612 v <<= 3;
1613 v += c - '0';
1614 c = pgetc();
1615 if (c >= '0' && c <= '7') {
1616 v <<= 3;
1617 v += c - '0';
1618 } else
1619 pungetc();
1620 } else
1621 pungetc();
1622 break;
1623
1624 case 'c':
1625 c = pgetc();
1626 if (c < 0x3f || c > 0x7a || c == 0x60)
1627 synerror("Bad \\c escape sequence");
1628 if (c == '\\' && pgetc() != '\\')
1629 synerror("Bad \\c\\ escape sequence");
1630 if (c == '?')
1631 v = 127;
1632 else
1633 v = c & 0x1f;
1634 break;
1635
1636 case 'x':
1637 n = 2;
1638 goto hexval;
1639 case 'u':
1640 n = 4;
1641 goto hexval;
1642 case 'U':
1643 n = 8;
1644 hexval:
1645 v = 0;
1646 for (i = 0; i < n; i++) {
1647 c = pgetc();
1648 if (c >= '0' && c <= '9')
1649 v = (v << 4) + c - '0';
1650 else if (c >= 'A' && c <= 'F')
1651 v = (v << 4) + c - 'A' + 10;
1652 else if (c >= 'a' && c <= 'f')
1653 v = (v << 4) + c - 'a' + 10;
1654 else {
1655 pungetc();
1656 break;
1657 }
1658 }
1659 if (n > 2 && v > 127) {
1660 if (v >= 0xd800 && v <= 0xdfff)
1661 synerror("Invalid \\u escape sequence");
1662
1663 /* XXX should we use iconv here. What locale? */
1664 CHECKSTRSPACE(4, out);
1665
1666 if (v <= 0x7ff) {
1667 USTPUTC(0xc0 | v >> 6, out);
1668 USTPUTC(0x80 | (v & 0x3f), out);
1669 return out;
1670 } else if (v <= 0xffff) {
1671 USTPUTC(0xe0 | v >> 12, out);
1672 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1673 USTPUTC(0x80 | (v & 0x3f), out);
1674 return out;
1675 } else if (v <= 0x10ffff) {
1676 USTPUTC(0xf0 | v >> 18, out);
1677 USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
1678 USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
1679 USTPUTC(0x80 | (v & 0x3f), out);
1680 return out;
1681 }
1682 if (v > 127)
1683 v = '?';
1684 }
1685 break;
1686 default:
1687 synerror("Unknown $'' escape sequence");
1688 }
1689 vc = (char)v;
1690
1691 /*
1692 * If we managed to create a \n from a \ sequence (no matter how)
1693 * then we replace it with the magic CRTCNL control char, which
1694 * will turn into a \n again later, but in the meantime, never
1695 * causes LINENO increments.
1696 */
1697 if (vc == '\n') {
1698 USTPUTC(CTLCNL, out);
1699 return out;
1700 }
1701
1702 /*
1703 * We can't handle NUL bytes.
1704 * POSIX says we should skip till the closing quote.
1705 */
1706 if (vc == '\0') {
1707 while ((c = pgetc()) != '\'') {
1708 if (c == '\\')
1709 c = pgetc();
1710 if (c == PEOF)
1711 synerror("Unterminated quoted string");
1712 if (c == '\n') {
1713 plinno++;
1714 if (doprompt)
1715 setprompt(2);
1716 else
1717 setprompt(0);
1718 }
1719 }
1720 pungetc();
1721 return out;
1722 }
1723 if (NEEDESC(vc))
1724 USTPUTC(CTLESC, out);
1725 USTPUTC(vc, out);
1726 return out;
1727 }
1728
1729 /*
1730 * The lowest level basic tokenizer.
1731 *
1732 * The next input byte (character) is in firstc, syn says which
1733 * syntax tables we are to use (basic, single or double quoted, or arith)
1734 * and magicq (used with sqsyntax and dqsyntax only) indicates that the
1735 * quote character itself is not special (used parsing here docs and similar)
1736 *
1737 * The result is the type of the next token (its value, when there is one,
1738 * is saved in the relevant global var - must fix that someday!) which is
1739 * also saved for re-reading ("lasttoken").
1740 *
1741 * Overall, this routine does far more parsing than it is supposed to.
1742 * That will also need fixing, someday...
1743 */
1744 STATIC int
1745 readtoken1(int firstc, char const *syn, int magicq)
1746 {
1747 int c;
1748 char * out;
1749 int len;
1750 struct nodelist *bqlist;
1751 int quotef;
1752 VSS static_stack;
1753 VSS *stack = &static_stack;
1754
1755 stack->prev = NULL;
1756 stack->cur = 0;
1757
1758 syntax = syn;
1759
1760 startlinno = plinno;
1761 varnest = 0;
1762 quoted = 0;
1763 if (syntax == DQSYNTAX)
1764 SETDBLQUOTE();
1765 quotef = 0;
1766 bqlist = NULL;
1767 arinest = 0;
1768 parenlevel = 0;
1769 elided_nl = 0;
1770
1771 STARTSTACKSTR(out);
1772
1773 for (c = firstc ;; c = pgetc_macro()) { /* until of token */
1774 if (syntax == ARISYNTAX)
1775 out = insert_elided_nl(out);
1776 CHECKSTRSPACE(6, out); /* permit 6 calls to USTPUTC */
1777 switch (syntax[c]) {
1778 case CFAKE:
1779 if (syntax == BASESYNTAX && varnest == 0)
1780 break;
1781 continue;
1782 case CNL: /* '\n' */
1783 if (syntax == BASESYNTAX && varnest == 0)
1784 break; /* exit loop */
1785 USTPUTC(c, out);
1786 plinno++;
1787 if (doprompt)
1788 setprompt(2);
1789 else
1790 setprompt(0);
1791 continue;
1792
1793 case CSBACK: /* single quoted backslash */
1794 if ((quoted & QF) == CQ) {
1795 out = readcstyleesc(out);
1796 continue;
1797 }
1798 USTPUTC(CTLESC, out);
1799 /* FALLTHROUGH */
1800 case CWORD:
1801 USTPUTC(c, out);
1802 continue;
1803
1804 case CCTL:
1805 if (!magicq || ISDBLQUOTE())
1806 USTPUTC(CTLESC, out);
1807 USTPUTC(c, out);
1808 continue;
1809 case CBACK: /* backslash */
1810 c = pgetc();
1811 if (c == PEOF) {
1812 USTPUTC('\\', out);
1813 pungetc();
1814 continue;
1815 }
1816 if (c == '\n') {
1817 plinno++;
1818 elided_nl++;
1819 if (doprompt)
1820 setprompt(2);
1821 else
1822 setprompt(0);
1823 continue;
1824 }
1825 quotef = 1; /* current token is quoted */
1826 if (ISDBLQUOTE() && c != '\\' && c != '`' &&
1827 c != '$' && (c != '"' || magicq)) {
1828 /*
1829 * retain the \ (which we *know* needs CTLESC)
1830 * when in "..." and the following char is
1831 * not one of the magic few.)
1832 * Otherwise the \ has done its work, and
1833 * is dropped.
1834 */
1835 USTPUTC(CTLESC, out);
1836 USTPUTC('\\', out);
1837 }
1838 if (NEEDESC(c))
1839 USTPUTC(CTLESC, out);
1840 else if (!magicq) {
1841 USTPUTC(CTLESC, out);
1842 USTPUTC(c, out);
1843 continue;
1844 }
1845 USTPUTC(c, out);
1846 continue;
1847 case CSQUOTE:
1848 if (syntax != SQSYNTAX) {
1849 if (!magicq)
1850 USTPUTC(CTLQUOTEMARK, out);
1851 quotef = 1;
1852 TS_PUSH();
1853 syntax = SQSYNTAX;
1854 quoted = SQ;
1855 continue;
1856 }
1857 if (magicq && arinest == 0 && varnest == 0) {
1858 /* Ignore inside quoted here document */
1859 USTPUTC(c, out);
1860 continue;
1861 }
1862 /* End of single quotes... */
1863 TS_POP();
1864 if (syntax == BASESYNTAX)
1865 USTPUTC(CTLQUOTEEND, out);
1866 continue;
1867 case CDQUOTE:
1868 if (magicq && arinest == 0 && varnest == 0) {
1869 /* Ignore inside here document */
1870 USTPUTC(c, out);
1871 continue;
1872 }
1873 quotef = 1;
1874 if (arinest) {
1875 if (ISDBLQUOTE()) {
1876 USTPUTC(CTLQUOTEEND, out);
1877 TS_POP();
1878 } else {
1879 TS_PUSH();
1880 syntax = DQSYNTAX;
1881 SETDBLQUOTE();
1882 USTPUTC(CTLQUOTEMARK, out);
1883 }
1884 continue;
1885 }
1886 if (magicq)
1887 continue;
1888 if (ISDBLQUOTE()) {
1889 TS_POP();
1890 USTPUTC(CTLQUOTEEND, out);
1891 } else {
1892 TS_PUSH();
1893 syntax = DQSYNTAX;
1894 SETDBLQUOTE();
1895 USTPUTC(CTLQUOTEMARK, out);
1896 }
1897 continue;
1898 case CVAR: /* '$' */
1899 out = insert_elided_nl(out);
1900 PARSESUB(); /* parse substitution */
1901 continue;
1902 case CENDVAR: /* CLOSEBRACE */
1903 if (varnest > 0 && !ISDBLQUOTE()) {
1904 TS_POP();
1905 USTPUTC(CTLENDVAR, out);
1906 } else {
1907 USTPUTC(c, out);
1908 }
1909 out = insert_elided_nl(out);
1910 continue;
1911 case CLP: /* '(' in arithmetic */
1912 parenlevel++;
1913 USTPUTC(c, out);
1914 continue;;
1915 case CRP: /* ')' in arithmetic */
1916 if (parenlevel > 0) {
1917 USTPUTC(c, out);
1918 --parenlevel;
1919 } else {
1920 if (pgetc_linecont() == /*(*/ ')') {
1921 out = insert_elided_nl(out);
1922 if (--arinest == 0) {
1923 TS_POP();
1924 USTPUTC(CTLENDARI, out);
1925 } else
1926 USTPUTC(/*(*/ ')', out);
1927 } else {
1928 break; /* to synerror() just below */
1929 #if 0 /* the old way, causes weird errors on bad input */
1930 /*
1931 * unbalanced parens
1932 * (don't 2nd guess - no error)
1933 */
1934 pungetc();
1935 USTPUTC(/*(*/ ')', out);
1936 #endif
1937 }
1938 }
1939 continue;
1940 case CBQUOTE: /* '`' */
1941 out = parsebackq(stack, out, &bqlist, 1, magicq);
1942 continue;
1943 case CEOF: /* --> c == PEOF */
1944 break; /* will exit loop */
1945 default:
1946 if (varnest == 0 && !ISDBLQUOTE())
1947 break; /* exit loop */
1948 USTPUTC(c, out);
1949 continue;
1950 }
1951 break; /* break from switch -> break from for loop too */
1952 }
1953
1954 if (syntax == ARISYNTAX) {
1955 cleanup_state_stack(stack);
1956 synerror(/*((*/ "Missing '))'");
1957 }
1958 if (syntax != BASESYNTAX && /* ! parsebackquote && */ !magicq) {
1959 cleanup_state_stack(stack);
1960 synerror("Unterminated quoted string");
1961 }
1962 if (varnest != 0) {
1963 cleanup_state_stack(stack);
1964 startlinno = plinno;
1965 /* { */
1966 synerror("Missing '}'");
1967 }
1968
1969 STPUTC('\0', out);
1970 len = out - stackblock();
1971 out = stackblock();
1972
1973 if (!magicq) {
1974 if ((c == '<' || c == '>')
1975 && quotef == 0 && (*out == '\0' || is_number(out))) {
1976 parseredir(out, c);
1977 cleanup_state_stack(stack);
1978 return lasttoken = TREDIR;
1979 } else {
1980 pungetc();
1981 }
1982 }
1983
1984 VTRACE(DBG_PARSE,
1985 ("readtoken1 %sword \"%s\", completed%s (%d) left %d enl\n",
1986 (quotef ? "quoted " : ""), out, (bqlist ? " with cmdsubs" : ""),
1987 len, elided_nl));
1988
1989 quoteflag = quotef;
1990 backquotelist = bqlist;
1991 grabstackblock(len);
1992 wordtext = out;
1993 cleanup_state_stack(stack);
1994 return lasttoken = TWORD;
1995 /* end of readtoken routine */
1996
1997
1998 /*
1999 * Parse a substitution. At this point, we have read the dollar sign
2000 * and nothing else.
2001 */
2002
2003 parsesub: {
2004 int subtype;
2005 int typeloc;
2006 int flags;
2007 char *p;
2008 static const char types[] = "}-+?=";
2009
2010 c = pgetc_linecont();
2011 if (c == '(' /*)*/) { /* $(command) or $((arith)) */
2012 if (pgetc_linecont() == '(' /*')'*/ ) {
2013 out = insert_elided_nl(out);
2014 PARSEARITH();
2015 } else {
2016 out = insert_elided_nl(out);
2017 pungetc();
2018 out = parsebackq(stack, out, &bqlist, 0, magicq);
2019 }
2020 } else if (c == OPENBRACE || is_name(c) || is_special(c)) {
2021 USTPUTC(CTLVAR, out);
2022 typeloc = out - stackblock();
2023 USTPUTC(VSNORMAL, out);
2024 subtype = VSNORMAL;
2025 flags = 0;
2026 if (c == OPENBRACE) {
2027 c = pgetc_linecont();
2028 if (c == '#') {
2029 if ((c = pgetc_linecont()) == CLOSEBRACE)
2030 c = '#';
2031 else if (is_name(c) || isdigit(c))
2032 subtype = VSLENGTH;
2033 else if (is_special(c)) {
2034 /*
2035 * ${#} is $# - the number of sh params
2036 * ${##} is the length of ${#}
2037 * ${###} is ${#} with as much nothing
2038 * as possible removed from start
2039 * ${##1} is ${#} with leading 1 gone
2040 * ${##\#} is ${#} with leading # gone
2041 *
2042 * this stuff is UGLY!
2043 */
2044 if (pgetc_linecont() == CLOSEBRACE) {
2045 pungetc();
2046 subtype = VSLENGTH;
2047 } else {
2048 static char cbuf[2];
2049
2050 pungetc(); /* would like 2 */
2051 cbuf[0] = c; /* so ... */
2052 cbuf[1] = '\0';
2053 pushstring(cbuf, 1, NULL);
2054 c = '#'; /* ${#:...} */
2055 subtype = 0; /* .. or similar */
2056 }
2057 } else {
2058 pungetc();
2059 c = '#';
2060 subtype = 0;
2061 }
2062 }
2063 else
2064 subtype = 0;
2065 }
2066 if (is_name(c)) {
2067 p = out;
2068 do {
2069 STPUTC(c, out);
2070 c = pgetc_linecont();
2071 } while (is_in_name(c));
2072 #if 0
2073 if (out - p == 6 && strncmp(p, "LINENO", 6) == 0) {
2074 int i;
2075 int linno;
2076 char buf[10];
2077
2078 /*
2079 * The "LINENO hack"
2080 *
2081 * Replace the variable name with the
2082 * current line number.
2083 */
2084 linno = plinno;
2085 if (funclinno != 0)
2086 linno -= funclinno - 1;
2087 snprintf(buf, sizeof(buf), "%d", linno);
2088 STADJUST(-6, out);
2089 for (i = 0; buf[i] != '\0'; i++)
2090 STPUTC(buf[i], out);
2091 flags |= VSLINENO;
2092 }
2093 #endif
2094 } else if (is_digit(c)) {
2095 do {
2096 STPUTC(c, out);
2097 c = pgetc_linecont();
2098 } while (subtype != VSNORMAL && is_digit(c));
2099 }
2100 else if (is_special(c)) {
2101 USTPUTC(c, out);
2102 c = pgetc_linecont();
2103 }
2104 else {
2105 badsub:
2106 cleanup_state_stack(stack);
2107 synerror("Bad substitution");
2108 }
2109
2110 STPUTC('=', out);
2111 if (subtype == 0) {
2112 switch (c) {
2113 case ':':
2114 flags |= VSNUL;
2115 c = pgetc_linecont();
2116 /*FALLTHROUGH*/
2117 default:
2118 p = strchr(types, c);
2119 if (p == NULL)
2120 goto badsub;
2121 subtype = p - types + VSNORMAL;
2122 break;
2123 case '%':
2124 case '#':
2125 {
2126 int cc = c;
2127 subtype = c == '#' ? VSTRIMLEFT :
2128 VSTRIMRIGHT;
2129 c = pgetc_linecont();
2130 if (c == cc)
2131 subtype++;
2132 else
2133 pungetc();
2134 break;
2135 }
2136 }
2137 } else {
2138 if (subtype == VSLENGTH && c != /*{*/ '}')
2139 synerror("no modifiers allowed with ${#var}");
2140 pungetc();
2141 }
2142 if (quoted || arinest)
2143 flags |= VSQUOTE;
2144 if (subtype >= VSTRIMLEFT && subtype <= VSTRIMRIGHTMAX)
2145 flags |= VSPATQ;
2146 *(stackblock() + typeloc) = subtype | flags;
2147 if (subtype != VSNORMAL) {
2148 TS_PUSH();
2149 varnest++;
2150 arinest = 0;
2151 if (subtype > VSASSIGN) { /* # ## % %% */
2152 syntax = BASESYNTAX;
2153 quoted = 0;
2154 }
2155 }
2156 } else if (c == '\'' && syntax == BASESYNTAX) {
2157 USTPUTC(CTLQUOTEMARK, out);
2158 quotef = 1;
2159 TS_PUSH();
2160 syntax = SQSYNTAX;
2161 quoted = CQ;
2162 } else {
2163 USTPUTC('$', out);
2164 pungetc();
2165 }
2166 goto parsesub_return;
2167 }
2168
2169
2170 /*
2171 * Parse an arithmetic expansion (indicate start of one and set state)
2172 */
2173 parsearith: {
2174
2175 #if 0
2176 if (syntax == ARISYNTAX) {
2177 /*
2178 * we collapse embedded arithmetic expansion to
2179 * parentheses, which should be equivalent
2180 *
2181 * XXX It isn't, must fix, soonish...
2182 */
2183 USTPUTC('(' /*)*/, out);
2184 USTPUTC('(' /*)*/, out);
2185 /*
2186 * Need 2 of them because there will (should be)
2187 * two closing ))'s to follow later.
2188 */
2189 parenlevel += 2;
2190 } else
2191 #endif
2192 {
2193 USTPUTC(CTLARI, out);
2194 if (ISDBLQUOTE())
2195 USTPUTC('"',out);
2196 else
2197 USTPUTC(' ',out);
2198
2199 TS_PUSH();
2200 syntax = ARISYNTAX;
2201 arinest = 1;
2202 varnest = 0;
2203 }
2204 goto parsearith_return;
2205 }
2206
2207 } /* end of readtoken */
2208
2209
2210
2211
2212 #ifdef mkinit
2213 INCLUDE "parser.h"
2214
2215 RESET {
2216 psp.v_current_parser = &parse_state;
2217
2218 parse_state.ps_tokpushback = 0;
2219 parse_state.ps_checkkwd = 0;
2220 parse_state.ps_heredoclist = NULL;
2221 }
2222 #endif
2223
2224 /*
2225 * Returns true if the text contains nothing to expand (no dollar signs
2226 * or backquotes).
2227 */
2228
2229 STATIC int
2230 noexpand(char *text)
2231 {
2232 char *p;
2233 char c;
2234
2235 p = text;
2236 while ((c = *p++) != '\0') {
2237 if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
2238 continue;
2239 if (c == CTLESC)
2240 p++;
2241 else if (BASESYNTAX[(int)c] == CCTL)
2242 return 0;
2243 }
2244 return 1;
2245 }
2246
2247
2248 /*
2249 * Return true if the argument is a legal variable name (a letter or
2250 * underscore followed by zero or more letters, underscores, and digits).
2251 */
2252
2253 int
2254 goodname(const char *name)
2255 {
2256 const char *p;
2257
2258 p = name;
2259 if (! is_name(*p))
2260 return 0;
2261 while (*++p) {
2262 if (! is_in_name(*p))
2263 return 0;
2264 }
2265 return 1;
2266 }
2267
2268 int
2269 isassignment(const char *p)
2270 {
2271 if (!is_name(*p))
2272 return 0;
2273 while (*++p != '=')
2274 if (*p == '\0' || !is_in_name(*p))
2275 return 0;
2276 return 1;
2277 }
2278
2279 /*
2280 * skip past any \n's, and leave lasttoken set to whatever follows
2281 */
2282 STATIC void
2283 linebreak(void)
2284 {
2285 while (readtoken() == TNL)
2286 ;
2287 }
2288
2289 /*
2290 * The next token must be "token" -- check, then move past it
2291 */
2292 STATIC void
2293 consumetoken(int token)
2294 {
2295 if (readtoken() != token) {
2296 VTRACE(DBG_PARSE, ("consumetoken(%d): expecting %s got %s",
2297 token, tokname[token], tokname[lasttoken]));
2298 CVTRACE(DBG_PARSE, (lasttoken==TWORD), (" \"%s\"", wordtext));
2299 VTRACE(DBG_PARSE, ("\n"));
2300 synexpect(token, NULL);
2301 }
2302 }
2303
2304 /*
2305 * Called when an unexpected token is read during the parse. The argument
2306 * is the token that is expected, or -1 if more than one type of token can
2307 * occur at this point.
2308 */
2309
2310 STATIC void
2311 synexpect(int token, const char *text)
2312 {
2313 char msg[64];
2314 char *p;
2315
2316 if (lasttoken == TWORD) {
2317 size_t len = strlen(wordtext);
2318
2319 if (len <= 13)
2320 fmtstr(msg, 34, "Word \"%.13s\" unexpected", wordtext);
2321 else
2322 fmtstr(msg, 34,
2323 "Word \"%.10s...\" unexpected", wordtext);
2324 } else
2325 fmtstr(msg, 34, "%s unexpected", tokname[lasttoken]);
2326
2327 p = strchr(msg, '\0');
2328 if (text)
2329 fmtstr(p, 30, " (expecting \"%.10s\")", text);
2330 else if (token >= 0)
2331 fmtstr(p, 30, " (expecting %s)", tokname[token]);
2332
2333 synerror(msg);
2334 /* NOTREACHED */
2335 }
2336
2337
2338 STATIC void
2339 synerror(const char *msg)
2340 {
2341 error("%d: Syntax error: %s", startlinno, msg);
2342 /* NOTREACHED */
2343 }
2344
2345 STATIC void
2346 setprompt(int which)
2347 {
2348 whichprompt = which;
2349
2350 #ifndef SMALL
2351 if (!el)
2352 #endif
2353 out2str(getprompt(NULL));
2354 }
2355
2356 /*
2357 * handle getting the next character, while ignoring \ \n
2358 * (which is a little tricky as we only have one char of pushback
2359 * and we need that one elsewhere).
2360 */
2361 STATIC int
2362 pgetc_linecont(void)
2363 {
2364 int c;
2365
2366 while ((c = pgetc_macro()) == '\\') {
2367 c = pgetc();
2368 if (c == '\n') {
2369 plinno++;
2370 elided_nl++;
2371 if (doprompt)
2372 setprompt(2);
2373 else
2374 setprompt(0);
2375 } else {
2376 pungetc();
2377 /* Allow the backslash to be pushed back. */
2378 pushstring("\\", 1, NULL);
2379 return (pgetc());
2380 }
2381 }
2382 return (c);
2383 }
2384
2385 /*
2386 * called by editline -- any expansions to the prompt
2387 * should be added here.
2388 */
2389 const char *
2390 getprompt(void *unused)
2391 {
2392 char *p;
2393 const char *cp;
2394 int wp;
2395
2396 if (!doprompt)
2397 return "";
2398
2399 VTRACE(DBG_PARSE|DBG_EXPAND, ("getprompt %d\n", whichprompt));
2400
2401 switch (wp = whichprompt) {
2402 case 0:
2403 return "";
2404 case 1:
2405 p = ps1val();
2406 break;
2407 case 2:
2408 p = ps2val();
2409 break;
2410 default:
2411 return "<internal prompt error>";
2412 }
2413 if (p == NULL)
2414 return "";
2415
2416 VTRACE(DBG_PARSE|DBG_EXPAND, ("prompt <<%s>>\n", p));
2417
2418 cp = expandstr(p, plinno);
2419 whichprompt = wp; /* history depends on it not changing */
2420
2421 VTRACE(DBG_PARSE|DBG_EXPAND, ("prompt -> <<%s>>\n", cp));
2422
2423 return cp;
2424 }
2425
2426 /*
2427 * Expand a string ... used for expanding prompts (PS1...)
2428 *
2429 * Never return NULL, always some string (return input string if invalid)
2430 *
2431 * The internal routine does the work, leaving the result on the
2432 * stack (or in a static string, or even the input string) and
2433 * handles parser recursion, and cleanup after an error while parsing.
2434 *
2435 * The visible interface copies the result off the stack (if it is there),
2436 * and handles stack management, leaving the stack in the exact same
2437 * state it was when expandstr() was called (so it can be used part way
2438 * through building a stack data structure - as in when PS2 is being
2439 * expanded half way through reading a "command line")
2440 *
2441 * on error, expandonstack() cleans up the parser state, but then
2442 * simply jumps out through expandstr() withut doing any stack cleanup,
2443 * which is OK, as the error handler must deal with that anyway.
2444 *
2445 * The split into two funcs is to avoid problems with setjmp/longjmp
2446 * and local variables which could otherwise be optimised into bizarre
2447 * behaviour.
2448 */
2449 static const char *
2450 expandonstack(char *ps, int lineno)
2451 {
2452 union node n;
2453 struct jmploc jmploc;
2454 struct jmploc *const savehandler = handler;
2455 struct parsefile *const savetopfile = getcurrentfile();
2456 const int save_x = xflag;
2457 struct parse_state new_state = init_parse_state;
2458 struct parse_state *const saveparser = psp.v_current_parser;
2459 const char *result = NULL;
2460
2461 if (!setjmp(jmploc.loc)) {
2462 handler = &jmploc;
2463
2464 psp.v_current_parser = &new_state;
2465 setinputstring(ps, 1, lineno);
2466
2467 readtoken1(pgetc(), DQSYNTAX, 1);
2468 if (backquotelist != NULL && !promptcmds)
2469 result = "-o promptcmds not set: ";
2470 else {
2471 n.narg.type = NARG;
2472 n.narg.next = NULL;
2473 n.narg.text = wordtext;
2474 n.narg.lineno = lineno;
2475 n.narg.backquote = backquotelist;
2476
2477 xflag = 0; /* we might be expanding PS4 ... */
2478 expandarg(&n, NULL, 0);
2479 result = stackblock();
2480 }
2481 INTOFF;
2482 }
2483 psp.v_current_parser = saveparser;
2484 xflag = save_x;
2485 popfilesupto(savetopfile);
2486 handler = savehandler;
2487
2488 if (exception == EXEXIT)
2489 longjmp(handler->loc, 1);
2490
2491 if (result != NULL) {
2492 INTON;
2493 } else {
2494 if (exception == EXINT)
2495 exraise(SIGINT);
2496 result = ps;
2497 }
2498
2499 return result;
2500 }
2501
2502 const char *
2503 expandstr(char *ps, int lineno)
2504 {
2505 const char *result = NULL;
2506 struct stackmark smark;
2507 static char *buffer = NULL; /* storage for prompt, never freed */
2508 static size_t bufferlen = 0;
2509
2510 setstackmark(&smark);
2511 /*
2512 * At this point we anticipate that there may be a string
2513 * growing on the stack, but we have no idea how big it is.
2514 * However we know that it cannot be bigger than the current
2515 * allocated stack block, so simply reserve the whole thing,
2516 * then we can use the stack without barfing all over what
2517 * is there already... (the stack mark undoes this later.)
2518 */
2519 (void) stalloc(stackblocksize());
2520
2521 result = expandonstack(ps, lineno);
2522
2523 if (__predict_true(result == stackblock())) {
2524 size_t len = strlen(result) + 1;
2525
2526 /*
2527 * the result (usual case) is on the stack, which we
2528 * are just about to discard (popstackmark()) so we
2529 * need to move it somewhere safe first.
2530 */
2531
2532 if (__predict_false(len > bufferlen)) {
2533 char *new;
2534 size_t newlen = bufferlen;
2535
2536 if (__predict_false(len > (SIZE_MAX >> 4))) {
2537 result = "huge prompt: ";
2538 goto getout;
2539 }
2540
2541 if (newlen == 0)
2542 newlen = 32;
2543 while (newlen <= len)
2544 newlen <<= 1;
2545
2546 new = (char *)realloc(buffer, newlen);
2547
2548 if (__predict_false(new == NULL)) {
2549 /*
2550 * this should rarely (if ever) happen
2551 * but we must do something when it does...
2552 */
2553 result = "No mem for prompt: ";
2554 goto getout;
2555 } else {
2556 buffer = new;
2557 bufferlen = newlen;
2558 }
2559 }
2560 (void)memcpy(buffer, result, len);
2561 result = buffer;
2562 }
2563
2564 getout:;
2565 popstackmark(&smark);
2566
2567 return result;
2568 }
2569