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 } 1283 pungetc(); 1284 return out; 1285 } 1286 if (SQSYNTAX[v] == CCTL) 1287 USTPUTC(CTLESC, out); 1288 USTPUTC(v, out); 1289 return out; 1290 } 1291 1292 1293 /* 1294 * If eofmark is NULL, read a word or a redirection symbol. If eofmark 1295 * is not NULL, read a here document. In the latter case, eofmark is the 1296 * word which marks the end of the document and striptabs is true if 1297 * leading tabs should be stripped from the document. The argument firstc 1298 * is the first character of the input token or document. 1299 * 1300 * Because C does not have internal subroutines, I have simulated them 1301 * using goto's to implement the subroutine linkage. The following macros 1302 * will run code that appears at the end of readtoken1. 1303 */ 1304 1305 #define PARSEREDIR() {goto parseredir; parseredir_return:;} 1306 #define PARSESUB() {goto parsesub; parsesub_return:;} 1307 #define PARSEARITH() {goto parsearith; parsearith_return:;} 1308 1309 static int 1310 readtoken1(int firstc, char const *initialsyntax, const char *eofmark, 1311 int striptabs) 1312 { 1313 int c = firstc; 1314 char *out; 1315 int len; 1316 struct nodelist *bqlist; 1317 int quotef; 1318 int newvarnest; 1319 int level; 1320 int synentry; 1321 struct tokenstate state_static[MAXNEST_static]; 1322 int maxnest = MAXNEST_static; 1323 struct tokenstate *state = state_static; 1324 int sqiscstyle = 0; 1325 1326 startlinno = plinno; 1327 quotef = 0; 1328 bqlist = NULL; 1329 newvarnest = 0; 1330 level = 0; 1331 state[level].syntax = initialsyntax; 1332 state[level].parenlevel = 0; 1333 state[level].category = TSTATE_TOP; 1334 1335 STARTSTACKSTR(out); 1336 loop: { /* for each line, until end of word */ 1337 if (eofmark) 1338 /* set c to PEOF if at end of here document */ 1339 c = checkend(c, eofmark, striptabs); 1340 for (;;) { /* until end of line or end of word */ 1341 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */ 1342 1343 synentry = state[level].syntax[c]; 1344 1345 switch(synentry) { 1346 case CNL: /* '\n' */ 1347 if (state[level].syntax == BASESYNTAX) 1348 goto endword; /* exit outer loop */ 1349 USTPUTC(c, out); 1350 plinno++; 1351 if (doprompt) 1352 setprompt(2); 1353 else 1354 setprompt(0); 1355 c = pgetc(); 1356 goto loop; /* continue outer loop */ 1357 case CSBACK: 1358 if (sqiscstyle) { 1359 out = readcstyleesc(out); 1360 break; 1361 } 1362 /* FALLTHROUGH */ 1363 case CWORD: 1364 USTPUTC(c, out); 1365 break; 1366 case CCTL: 1367 if (eofmark == NULL || initialsyntax != SQSYNTAX) 1368 USTPUTC(CTLESC, out); 1369 USTPUTC(c, out); 1370 break; 1371 case CBACK: /* backslash */ 1372 c = pgetc(); 1373 if (c == PEOF) { 1374 USTPUTC('\\', out); 1375 pungetc(); 1376 } else if (c == '\n') { 1377 plinno++; 1378 if (doprompt) 1379 setprompt(2); 1380 else 1381 setprompt(0); 1382 } else { 1383 if (state[level].syntax == DQSYNTAX && 1384 c != '\\' && c != '`' && c != '$' && 1385 (c != '"' || (eofmark != NULL && 1386 newvarnest == 0)) && 1387 (c != '}' || state[level].category != TSTATE_VAR_OLD)) 1388 USTPUTC('\\', out); 1389 if ((eofmark == NULL || 1390 newvarnest > 0) && 1391 state[level].syntax == BASESYNTAX) 1392 USTPUTC(CTLQUOTEMARK, out); 1393 if (SQSYNTAX[c] == CCTL) 1394 USTPUTC(CTLESC, out); 1395 USTPUTC(c, out); 1396 if ((eofmark == NULL || 1397 newvarnest > 0) && 1398 state[level].syntax == BASESYNTAX && 1399 state[level].category == TSTATE_VAR_OLD) 1400 USTPUTC(CTLQUOTEEND, out); 1401 quotef++; 1402 } 1403 break; 1404 case CSQUOTE: 1405 USTPUTC(CTLQUOTEMARK, out); 1406 state[level].syntax = SQSYNTAX; 1407 sqiscstyle = 0; 1408 break; 1409 case CDQUOTE: 1410 USTPUTC(CTLQUOTEMARK, out); 1411 state[level].syntax = DQSYNTAX; 1412 break; 1413 case CENDQUOTE: 1414 if (eofmark != NULL && newvarnest == 0) 1415 USTPUTC(c, out); 1416 else { 1417 if (state[level].category == TSTATE_VAR_OLD) 1418 USTPUTC(CTLQUOTEEND, out); 1419 state[level].syntax = BASESYNTAX; 1420 quotef++; 1421 } 1422 break; 1423 case CVAR: /* '$' */ 1424 PARSESUB(); /* parse substitution */ 1425 break; 1426 case CENDVAR: /* '}' */ 1427 if (level > 0 && 1428 ((state[level].category == TSTATE_VAR_OLD && 1429 state[level].syntax == 1430 state[level - 1].syntax) || 1431 (state[level].category == TSTATE_VAR_NEW && 1432 state[level].syntax == BASESYNTAX))) { 1433 if (state[level].category == TSTATE_VAR_NEW) 1434 newvarnest--; 1435 level--; 1436 USTPUTC(CTLENDVAR, out); 1437 } else { 1438 USTPUTC(c, out); 1439 } 1440 break; 1441 case CLP: /* '(' in arithmetic */ 1442 state[level].parenlevel++; 1443 USTPUTC(c, out); 1444 break; 1445 case CRP: /* ')' in arithmetic */ 1446 if (state[level].parenlevel > 0) { 1447 USTPUTC(c, out); 1448 --state[level].parenlevel; 1449 } else { 1450 if (pgetc() == ')') { 1451 if (level > 0 && 1452 state[level].category == TSTATE_ARITH) { 1453 level--; 1454 USTPUTC(CTLENDARI, out); 1455 } else 1456 USTPUTC(')', out); 1457 } else { 1458 /* 1459 * unbalanced parens 1460 * (don't 2nd guess - no error) 1461 */ 1462 pungetc(); 1463 USTPUTC(')', out); 1464 } 1465 } 1466 break; 1467 case CBQUOTE: /* '`' */ 1468 out = parsebackq(out, &bqlist, 1, 1469 state[level].syntax == DQSYNTAX && 1470 (eofmark == NULL || newvarnest > 0), 1471 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX); 1472 break; 1473 case CEOF: 1474 goto endword; /* exit outer loop */ 1475 case CIGN: 1476 break; 1477 default: 1478 if (level == 0) 1479 goto endword; /* exit outer loop */ 1480 USTPUTC(c, out); 1481 } 1482 c = pgetc_macro(); 1483 } 1484 } 1485 endword: 1486 if (state[level].syntax == ARISYNTAX) 1487 synerror("Missing '))'"); 1488 if (state[level].syntax != BASESYNTAX && eofmark == NULL) 1489 synerror("Unterminated quoted string"); 1490 if (state[level].category == TSTATE_VAR_OLD || 1491 state[level].category == TSTATE_VAR_NEW) { 1492 startlinno = plinno; 1493 synerror("Missing '}'"); 1494 } 1495 if (state != state_static) 1496 parser_temp_free_upto(state); 1497 USTPUTC('\0', out); 1498 len = out - stackblock(); 1499 out = stackblock(); 1500 if (eofmark == NULL) { 1501 if ((c == '>' || c == '<') 1502 && quotef == 0 1503 && len <= 2 1504 && (*out == '\0' || is_digit(*out))) { 1505 PARSEREDIR(); 1506 return lasttoken = TREDIR; 1507 } else { 1508 pungetc(); 1509 } 1510 } 1511 quoteflag = quotef; 1512 backquotelist = bqlist; 1513 grabstackblock(len); 1514 wordtext = out; 1515 return lasttoken = TWORD; 1516 /* end of readtoken routine */ 1517 1518 1519 /* 1520 * Parse a redirection operator. The variable "out" points to a string 1521 * specifying the fd to be redirected. The variable "c" contains the 1522 * first character of the redirection operator. 1523 */ 1524 1525 parseredir: { 1526 char fd = *out; 1527 union node *np; 1528 1529 np = (union node *)stalloc(sizeof (struct nfile)); 1530 if (c == '>') { 1531 np->nfile.fd = 1; 1532 c = pgetc(); 1533 if (c == '>') 1534 np->type = NAPPEND; 1535 else if (c == '&') 1536 np->type = NTOFD; 1537 else if (c == '|') 1538 np->type = NCLOBBER; 1539 else { 1540 np->type = NTO; 1541 pungetc(); 1542 } 1543 } else { /* c == '<' */ 1544 np->nfile.fd = 0; 1545 c = pgetc(); 1546 if (c == '<') { 1547 if (sizeof (struct nfile) != sizeof (struct nhere)) { 1548 np = (union node *)stalloc(sizeof (struct nhere)); 1549 np->nfile.fd = 0; 1550 } 1551 np->type = NHERE; 1552 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc)); 1553 heredoc->here = np; 1554 if ((c = pgetc()) == '-') { 1555 heredoc->striptabs = 1; 1556 } else { 1557 heredoc->striptabs = 0; 1558 pungetc(); 1559 } 1560 } else if (c == '&') 1561 np->type = NFROMFD; 1562 else if (c == '>') 1563 np->type = NFROMTO; 1564 else { 1565 np->type = NFROM; 1566 pungetc(); 1567 } 1568 } 1569 if (fd != '\0') 1570 np->nfile.fd = digit_val(fd); 1571 redirnode = np; 1572 goto parseredir_return; 1573 } 1574 1575 1576 /* 1577 * Parse a substitution. At this point, we have read the dollar sign 1578 * and nothing else. 1579 */ 1580 1581 parsesub: { 1582 char buf[10]; 1583 int subtype; 1584 int typeloc; 1585 int flags; 1586 char *p; 1587 static const char types[] = "}-+?="; 1588 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */ 1589 int linno; 1590 int length; 1591 int c1; 1592 1593 c = pgetc(); 1594 if (c == '(') { /* $(command) or $((arith)) */ 1595 if (pgetc() == '(') { 1596 PARSEARITH(); 1597 } else { 1598 pungetc(); 1599 out = parsebackq(out, &bqlist, 0, 1600 state[level].syntax == DQSYNTAX && 1601 (eofmark == NULL || newvarnest > 0), 1602 state[level].syntax == DQSYNTAX || 1603 state[level].syntax == ARISYNTAX); 1604 } 1605 } else if (c == '{' || is_name(c) || is_special(c)) { 1606 USTPUTC(CTLVAR, out); 1607 typeloc = out - stackblock(); 1608 USTPUTC(VSNORMAL, out); 1609 subtype = VSNORMAL; 1610 flags = 0; 1611 if (c == '{') { 1612 bracketed_name = 1; 1613 c = pgetc(); 1614 subtype = 0; 1615 } 1616 varname: 1617 if (!is_eof(c) && is_name(c)) { 1618 length = 0; 1619 do { 1620 STPUTC(c, out); 1621 c = pgetc(); 1622 length++; 1623 } while (!is_eof(c) && is_in_name(c)); 1624 if (length == 6 && 1625 strncmp(out - length, "LINENO", length) == 0) { 1626 /* Replace the variable name with the 1627 * current line number. */ 1628 linno = plinno; 1629 if (funclinno != 0) 1630 linno -= funclinno - 1; 1631 snprintf(buf, sizeof(buf), "%d", linno); 1632 STADJUST(-6, out); 1633 STPUTS(buf, out); 1634 flags |= VSLINENO; 1635 } 1636 } else if (is_digit(c)) { 1637 if (bracketed_name) { 1638 do { 1639 STPUTC(c, out); 1640 c = pgetc(); 1641 } while (is_digit(c)); 1642 } else { 1643 STPUTC(c, out); 1644 c = pgetc(); 1645 } 1646 } else if (is_special(c)) { 1647 c1 = c; 1648 c = pgetc(); 1649 if (subtype == 0 && c1 == '#') { 1650 subtype = VSLENGTH; 1651 if (strchr(types, c) == NULL && c != ':' && 1652 c != '#' && c != '%') 1653 goto varname; 1654 c1 = c; 1655 c = pgetc(); 1656 if (c1 != '}' && c == '}') { 1657 pungetc(); 1658 c = c1; 1659 goto varname; 1660 } 1661 pungetc(); 1662 c = c1; 1663 c1 = '#'; 1664 subtype = 0; 1665 } 1666 USTPUTC(c1, out); 1667 } else { 1668 subtype = VSERROR; 1669 if (c == '}') 1670 pungetc(); 1671 else if (c == '\n' || c == PEOF) 1672 synerror("Unexpected end of line in substitution"); 1673 else 1674 USTPUTC(c, out); 1675 } 1676 if (subtype == 0) { 1677 switch (c) { 1678 case ':': 1679 flags |= VSNUL; 1680 c = pgetc(); 1681 /*FALLTHROUGH*/ 1682 default: 1683 p = strchr(types, c); 1684 if (p == NULL) { 1685 if (c == '\n' || c == PEOF) 1686 synerror("Unexpected end of line in substitution"); 1687 if (flags == VSNUL) 1688 STPUTC(':', out); 1689 STPUTC(c, out); 1690 subtype = VSERROR; 1691 } else 1692 subtype = p - types + VSNORMAL; 1693 break; 1694 case '%': 1695 case '#': 1696 { 1697 int cc = c; 1698 subtype = c == '#' ? VSTRIMLEFT : 1699 VSTRIMRIGHT; 1700 c = pgetc(); 1701 if (c == cc) 1702 subtype++; 1703 else 1704 pungetc(); 1705 break; 1706 } 1707 } 1708 } else if (subtype != VSERROR) { 1709 if (subtype == VSLENGTH && c != '}') 1710 subtype = VSERROR; 1711 pungetc(); 1712 } 1713 STPUTC('=', out); 1714 if (state[level].syntax == DQSYNTAX || 1715 state[level].syntax == ARISYNTAX) 1716 flags |= VSQUOTE; 1717 *(stackblock() + typeloc) = subtype | flags; 1718 if (subtype != VSNORMAL) { 1719 if (level + 1 >= maxnest) { 1720 maxnest *= 2; 1721 if (state == state_static) { 1722 state = parser_temp_alloc( 1723 maxnest * sizeof(*state)); 1724 memcpy(state, state_static, 1725 MAXNEST_static * sizeof(*state)); 1726 } else 1727 state = parser_temp_realloc(state, 1728 maxnest * sizeof(*state)); 1729 } 1730 level++; 1731 state[level].parenlevel = 0; 1732 if (subtype == VSMINUS || subtype == VSPLUS || 1733 subtype == VSQUESTION || subtype == VSASSIGN) { 1734 /* 1735 * For operators that were in the Bourne shell, 1736 * inherit the double-quote state. 1737 */ 1738 state[level].syntax = state[level - 1].syntax; 1739 state[level].category = TSTATE_VAR_OLD; 1740 } else { 1741 /* 1742 * The other operators take a pattern, 1743 * so go to BASESYNTAX. 1744 * Also, ' and " are now special, even 1745 * in here documents. 1746 */ 1747 state[level].syntax = BASESYNTAX; 1748 state[level].category = TSTATE_VAR_NEW; 1749 newvarnest++; 1750 } 1751 } 1752 } else if (c == '\'' && state[level].syntax == BASESYNTAX) { 1753 /* $'cstylequotes' */ 1754 USTPUTC(CTLQUOTEMARK, out); 1755 state[level].syntax = SQSYNTAX; 1756 sqiscstyle = 1; 1757 } else { 1758 USTPUTC('$', out); 1759 pungetc(); 1760 } 1761 goto parsesub_return; 1762 } 1763 1764 1765 /* 1766 * Parse an arithmetic expansion (indicate start of one and set state) 1767 */ 1768 parsearith: { 1769 1770 if (level + 1 >= maxnest) { 1771 maxnest *= 2; 1772 if (state == state_static) { 1773 state = parser_temp_alloc( 1774 maxnest * sizeof(*state)); 1775 memcpy(state, state_static, 1776 MAXNEST_static * sizeof(*state)); 1777 } else 1778 state = parser_temp_realloc(state, 1779 maxnest * sizeof(*state)); 1780 } 1781 level++; 1782 state[level].syntax = ARISYNTAX; 1783 state[level].parenlevel = 0; 1784 state[level].category = TSTATE_ARITH; 1785 USTPUTC(CTLARI, out); 1786 if (state[level - 1].syntax == DQSYNTAX) 1787 USTPUTC('"',out); 1788 else 1789 USTPUTC(' ',out); 1790 goto parsearith_return; 1791 } 1792 1793 } /* end of readtoken */ 1794 1795 1796 /* 1797 * Returns true if the text contains nothing to expand (no dollar signs 1798 * or backquotes). 1799 */ 1800 1801 static int 1802 noexpand(char *text) 1803 { 1804 char *p; 1805 char c; 1806 1807 p = text; 1808 while ((c = *p++) != '\0') { 1809 if ( c == CTLQUOTEMARK) 1810 continue; 1811 if (c == CTLESC) 1812 p++; 1813 else if (BASESYNTAX[(int)c] == CCTL) 1814 return 0; 1815 } 1816 return 1; 1817 } 1818 1819 1820 /* 1821 * Return true if the argument is a legal variable name (a letter or 1822 * underscore followed by zero or more letters, underscores, and digits). 1823 */ 1824 1825 int 1826 goodname(const char *name) 1827 { 1828 const char *p; 1829 1830 p = name; 1831 if (! is_name(*p)) 1832 return 0; 1833 while (*++p) { 1834 if (! is_in_name(*p)) 1835 return 0; 1836 } 1837 return 1; 1838 } 1839 1840 1841 int 1842 isassignment(const char *p) 1843 { 1844 if (!is_name(*p)) 1845 return 0; 1846 p++; 1847 for (;;) { 1848 if (*p == '=') 1849 return 1; 1850 else if (!is_in_name(*p)) 1851 return 0; 1852 p++; 1853 } 1854 } 1855 1856 1857 static void 1858 consumetoken(int token) 1859 { 1860 if (readtoken() != token) 1861 synexpect(token); 1862 } 1863 1864 1865 /* 1866 * Called when an unexpected token is read during the parse. The argument 1867 * is the token that is expected, or -1 if more than one type of token can 1868 * occur at this point. 1869 */ 1870 1871 static void 1872 synexpect(int token) 1873 { 1874 char msg[64]; 1875 1876 if (token >= 0) { 1877 fmtstr(msg, 64, "%s unexpected (expecting %s)", 1878 tokname[lasttoken], tokname[token]); 1879 } else { 1880 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]); 1881 } 1882 synerror(msg); 1883 } 1884 1885 1886 static void 1887 synerror(const char *msg) 1888 { 1889 if (commandname) 1890 outfmt(out2, "%s: %d: ", commandname, startlinno); 1891 outfmt(out2, "Syntax error: %s\n", msg); 1892 error((char *)NULL); 1893 } 1894 1895 static void 1896 setprompt(int which) 1897 { 1898 whichprompt = which; 1899 1900 #ifndef NO_HISTORY 1901 if (!el) 1902 #endif 1903 { 1904 out2str(getprompt(NULL)); 1905 flushout(out2); 1906 } 1907 } 1908 1909 /* 1910 * called by editline -- any expansions to the prompt 1911 * should be added here. 1912 */ 1913 char * 1914 getprompt(void *unused __unused) 1915 { 1916 static char ps[PROMPTLEN]; 1917 const char *fmt; 1918 const char *pwd; 1919 int i, trim; 1920 static char internal_error[] = "??"; 1921 1922 /* 1923 * Select prompt format. 1924 */ 1925 switch (whichprompt) { 1926 case 0: 1927 fmt = nullstr; 1928 break; 1929 case 1: 1930 fmt = ps1val(); 1931 break; 1932 case 2: 1933 fmt = ps2val(); 1934 break; 1935 default: 1936 return internal_error; 1937 } 1938 1939 /* 1940 * Format prompt string. 1941 */ 1942 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++) 1943 if (*fmt == '\\') 1944 switch (*++fmt) { 1945 1946 /* 1947 * Hostname. 1948 * 1949 * \h specifies just the local hostname, 1950 * \H specifies fully-qualified hostname. 1951 */ 1952 case 'h': 1953 case 'H': 1954 ps[i] = '\0'; 1955 gethostname(&ps[i], PROMPTLEN - i); 1956 /* Skip to end of hostname. */ 1957 trim = (*fmt == 'h') ? '.' : '\0'; 1958 while ((ps[i+1] != '\0') && (ps[i+1] != trim)) 1959 i++; 1960 break; 1961 1962 /* 1963 * Working directory. 1964 * 1965 * \W specifies just the final component, 1966 * \w specifies the entire path. 1967 */ 1968 case 'W': 1969 case 'w': 1970 pwd = lookupvar("PWD"); 1971 if (pwd == NULL) 1972 pwd = "?"; 1973 if (*fmt == 'W' && 1974 *pwd == '/' && pwd[1] != '\0') 1975 strlcpy(&ps[i], strrchr(pwd, '/') + 1, 1976 PROMPTLEN - i); 1977 else 1978 strlcpy(&ps[i], pwd, PROMPTLEN - i); 1979 /* Skip to end of path. */ 1980 while (ps[i + 1] != '\0') 1981 i++; 1982 break; 1983 1984 /* 1985 * Superuser status. 1986 * 1987 * '$' for normal users, '#' for root. 1988 */ 1989 case '$': 1990 ps[i] = (geteuid() != 0) ? '$' : '#'; 1991 break; 1992 1993 /* 1994 * A literal \. 1995 */ 1996 case '\\': 1997 ps[i] = '\\'; 1998 break; 1999 2000 /* 2001 * Emit unrecognized formats verbatim. 2002 */ 2003 default: 2004 ps[i++] = '\\'; 2005 ps[i] = *fmt; 2006 break; 2007 } 2008 else 2009 ps[i] = *fmt; 2010 ps[i] = '\0'; 2011 return (ps); 2012 } 2013 2014 2015 const char * 2016 expandstr(const char *ps) 2017 { 2018 union node n; 2019 struct jmploc jmploc; 2020 struct jmploc *const savehandler = handler; 2021 const int saveprompt = doprompt; 2022 struct parsefile *const savetopfile = getcurrentfile(); 2023 struct parser_temp *const saveparser_temp = parser_temp; 2024 const char *result = NULL; 2025 2026 if (!setjmp(jmploc.loc)) { 2027 handler = &jmploc; 2028 parser_temp = NULL; 2029 setinputstring(ps, 1); 2030 doprompt = 0; 2031 readtoken1(pgetc(), DQSYNTAX, "", 0); 2032 if (backquotelist != NULL) 2033 error("Command substitution not allowed here"); 2034 2035 n.narg.type = NARG; 2036 n.narg.next = NULL; 2037 n.narg.text = wordtext; 2038 n.narg.backquote = backquotelist; 2039 2040 expandarg(&n, NULL, 0); 2041 result = stackblock(); 2042 INTOFF; 2043 } 2044 handler = savehandler; 2045 doprompt = saveprompt; 2046 popfilesupto(savetopfile); 2047 if (parser_temp != saveparser_temp) { 2048 parser_temp_free_all(); 2049 parser_temp = saveparser_temp; 2050 } 2051 if (result != NULL) { 2052 INTON; 2053 } else if (exception == EXINT) 2054 raise(SIGINT); 2055 return result; 2056 } 2057