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