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 /* FALLTHROUGH */ 893 default: 894 return readtoken1(c, BASESYNTAX, (char *)NULL, 0); 895 case '\n': 896 plinno++; 897 needprompt = doprompt; 898 RETURN(TNL); 899 case PEOF: 900 RETURN(TEOF); 901 case '&': 902 if (pgetc() == '&') 903 RETURN(TAND); 904 pungetc(); 905 RETURN(TBACKGND); 906 case '|': 907 if (pgetc() == '|') 908 RETURN(TOR); 909 pungetc(); 910 RETURN(TPIPE); 911 case ';': 912 c = pgetc(); 913 if (c == ';') 914 RETURN(TENDCASE); 915 else if (c == '&') 916 RETURN(TFALLTHRU); 917 pungetc(); 918 RETURN(TSEMI); 919 case '(': 920 RETURN(TLP); 921 case ')': 922 RETURN(TRP); 923 } 924 } 925 #undef RETURN 926 } 927 928 929 #define MAXNEST_static 8 930 struct tokenstate 931 { 932 const char *syntax; /* *SYNTAX */ 933 int parenlevel; /* levels of parentheses in arithmetic */ 934 enum tokenstate_category 935 { 936 TSTATE_TOP, 937 TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */ 938 TSTATE_VAR_NEW, /* other ${var...}, own dquote state */ 939 TSTATE_ARITH 940 } category; 941 }; 942 943 944 /* 945 * Check to see whether we are at the end of the here document. When this 946 * is called, c is set to the first character of the next input line. If 947 * we are at the end of the here document, this routine sets the c to PEOF. 948 * The new value of c is returned. 949 */ 950 951 static int 952 checkend(int c, const char *eofmark, int striptabs) 953 { 954 if (striptabs) { 955 while (c == '\t') 956 c = pgetc(); 957 } 958 if (c == *eofmark) { 959 int c2; 960 const char *q; 961 962 for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++) 963 ; 964 if ((c2 == PEOF || c2 == '\n') && *q == '\0') { 965 c = PEOF; 966 if (c2 == '\n') { 967 plinno++; 968 needprompt = doprompt; 969 } 970 } else { 971 pungetc(); 972 pushstring(eofmark + 1, q - (eofmark + 1), NULL); 973 } 974 } 975 return (c); 976 } 977 978 979 /* 980 * Parse a redirection operator. The variable "out" points to a string 981 * specifying the fd to be redirected. The variable "c" contains the 982 * first character of the redirection operator. 983 */ 984 985 static void 986 parseredir(char *out, int c) 987 { 988 char fd = *out; 989 union node *np; 990 991 np = (union node *)stalloc(sizeof (struct nfile)); 992 if (c == '>') { 993 np->nfile.fd = 1; 994 c = pgetc(); 995 if (c == '>') 996 np->type = NAPPEND; 997 else if (c == '&') 998 np->type = NTOFD; 999 else if (c == '|') 1000 np->type = NCLOBBER; 1001 else { 1002 np->type = NTO; 1003 pungetc(); 1004 } 1005 } else { /* c == '<' */ 1006 np->nfile.fd = 0; 1007 c = pgetc(); 1008 if (c == '<') { 1009 if (sizeof (struct nfile) != sizeof (struct nhere)) { 1010 np = (union node *)stalloc(sizeof (struct nhere)); 1011 np->nfile.fd = 0; 1012 } 1013 np->type = NHERE; 1014 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc)); 1015 heredoc->here = np; 1016 if ((c = pgetc()) == '-') { 1017 heredoc->striptabs = 1; 1018 } else { 1019 heredoc->striptabs = 0; 1020 pungetc(); 1021 } 1022 } else if (c == '&') 1023 np->type = NFROMFD; 1024 else if (c == '>') 1025 np->type = NFROMTO; 1026 else { 1027 np->type = NFROM; 1028 pungetc(); 1029 } 1030 } 1031 if (fd != '\0') 1032 np->nfile.fd = digit_val(fd); 1033 redirnode = np; 1034 } 1035 1036 /* 1037 * Called to parse command substitutions. 1038 */ 1039 1040 static char * 1041 parsebackq(char *out, struct nodelist **pbqlist, 1042 int oldstyle, int dblquote, int quoted) 1043 { 1044 struct nodelist **nlpp; 1045 union node *n; 1046 char *volatile str; 1047 struct jmploc jmploc; 1048 struct jmploc *const savehandler = handler; 1049 size_t savelen; 1050 int saveprompt; 1051 const int bq_startlinno = plinno; 1052 char *volatile ostr = NULL; 1053 struct parsefile *const savetopfile = getcurrentfile(); 1054 struct heredoc *const saveheredoclist = heredoclist; 1055 struct heredoc *here; 1056 1057 str = NULL; 1058 if (setjmp(jmploc.loc)) { 1059 popfilesupto(savetopfile); 1060 if (str) 1061 ckfree(str); 1062 if (ostr) 1063 ckfree(ostr); 1064 heredoclist = saveheredoclist; 1065 handler = savehandler; 1066 if (exception == EXERROR) { 1067 startlinno = bq_startlinno; 1068 synerror("Error in command substitution"); 1069 } 1070 longjmp(handler->loc, 1); 1071 } 1072 INTOFF; 1073 savelen = out - stackblock(); 1074 if (savelen > 0) { 1075 str = ckmalloc(savelen); 1076 memcpy(str, stackblock(), savelen); 1077 } 1078 handler = &jmploc; 1079 heredoclist = NULL; 1080 INTON; 1081 if (oldstyle) { 1082 /* We must read until the closing backquote, giving special 1083 treatment to some slashes, and then push the string and 1084 reread it as input, interpreting it normally. */ 1085 char *oout; 1086 int c; 1087 int olen; 1088 1089 1090 STARTSTACKSTR(oout); 1091 for (;;) { 1092 if (needprompt) { 1093 setprompt(2); 1094 needprompt = 0; 1095 } 1096 CHECKSTRSPACE(2, oout); 1097 c = pgetc(); 1098 if (c == '`') 1099 break; 1100 switch (c) { 1101 case '\\': 1102 if ((c = pgetc()) == '\n') { 1103 plinno++; 1104 if (doprompt) 1105 setprompt(2); 1106 else 1107 setprompt(0); 1108 /* 1109 * If eating a newline, avoid putting 1110 * the newline into the new character 1111 * stream (via the USTPUTC after the 1112 * switch). 1113 */ 1114 continue; 1115 } 1116 if (c != '\\' && c != '`' && c != '$' 1117 && (!dblquote || c != '"')) 1118 USTPUTC('\\', oout); 1119 break; 1120 1121 case '\n': 1122 plinno++; 1123 needprompt = doprompt; 1124 break; 1125 1126 case PEOF: 1127 startlinno = plinno; 1128 synerror("EOF in backquote substitution"); 1129 break; 1130 1131 default: 1132 break; 1133 } 1134 USTPUTC(c, oout); 1135 } 1136 USTPUTC('\0', oout); 1137 olen = oout - stackblock(); 1138 INTOFF; 1139 ostr = ckmalloc(olen); 1140 memcpy(ostr, stackblock(), olen); 1141 setinputstring(ostr, 1); 1142 INTON; 1143 } 1144 nlpp = pbqlist; 1145 while (*nlpp) 1146 nlpp = &(*nlpp)->next; 1147 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist)); 1148 (*nlpp)->next = NULL; 1149 1150 if (oldstyle) { 1151 saveprompt = doprompt; 1152 doprompt = 0; 1153 } 1154 1155 n = list(0); 1156 1157 if (oldstyle) { 1158 if (peektoken() != TEOF) 1159 synexpect(-1); 1160 doprompt = saveprompt; 1161 } else 1162 consumetoken(TRP); 1163 1164 (*nlpp)->n = n; 1165 if (oldstyle) { 1166 /* 1167 * Start reading from old file again, ignoring any pushed back 1168 * tokens left from the backquote parsing 1169 */ 1170 popfile(); 1171 tokpushback = 0; 1172 } 1173 STARTSTACKSTR(out); 1174 CHECKSTRSPACE(savelen + 1, out); 1175 INTOFF; 1176 if (str) { 1177 memcpy(out, str, savelen); 1178 STADJUST(savelen, out); 1179 ckfree(str); 1180 str = NULL; 1181 } 1182 if (ostr) { 1183 ckfree(ostr); 1184 ostr = NULL; 1185 } 1186 here = saveheredoclist; 1187 if (here != NULL) { 1188 while (here->next != NULL) 1189 here = here->next; 1190 here->next = heredoclist; 1191 heredoclist = saveheredoclist; 1192 } 1193 handler = savehandler; 1194 INTON; 1195 if (quoted) 1196 USTPUTC(CTLBACKQ | CTLQUOTE, out); 1197 else 1198 USTPUTC(CTLBACKQ, out); 1199 return out; 1200 } 1201 1202 1203 /* 1204 * Called to parse a backslash escape sequence inside $'...'. 1205 * The backslash has already been read. 1206 */ 1207 static char * 1208 readcstyleesc(char *out) 1209 { 1210 int c, v, i, n; 1211 1212 c = pgetc(); 1213 switch (c) { 1214 case '\0': 1215 synerror("Unterminated quoted string"); 1216 case '\n': 1217 plinno++; 1218 if (doprompt) 1219 setprompt(2); 1220 else 1221 setprompt(0); 1222 return out; 1223 case '\\': 1224 case '\'': 1225 case '"': 1226 v = c; 1227 break; 1228 case 'a': v = '\a'; break; 1229 case 'b': v = '\b'; break; 1230 case 'e': v = '\033'; break; 1231 case 'f': v = '\f'; break; 1232 case 'n': v = '\n'; break; 1233 case 'r': v = '\r'; break; 1234 case 't': v = '\t'; break; 1235 case 'v': v = '\v'; break; 1236 case 'x': 1237 v = 0; 1238 for (;;) { 1239 c = pgetc(); 1240 if (c >= '0' && c <= '9') 1241 v = (v << 4) + c - '0'; 1242 else if (c >= 'A' && c <= 'F') 1243 v = (v << 4) + c - 'A' + 10; 1244 else if (c >= 'a' && c <= 'f') 1245 v = (v << 4) + c - 'a' + 10; 1246 else 1247 break; 1248 } 1249 pungetc(); 1250 break; 1251 case '0': case '1': case '2': case '3': 1252 case '4': case '5': case '6': case '7': 1253 v = c - '0'; 1254 c = pgetc(); 1255 if (c >= '0' && c <= '7') { 1256 v <<= 3; 1257 v += c - '0'; 1258 c = pgetc(); 1259 if (c >= '0' && c <= '7') { 1260 v <<= 3; 1261 v += c - '0'; 1262 } else 1263 pungetc(); 1264 } else 1265 pungetc(); 1266 break; 1267 case 'c': 1268 c = pgetc(); 1269 if (c < 0x3f || c > 0x7a || c == 0x60) 1270 synerror("Bad escape sequence"); 1271 if (c == '\\' && pgetc() != '\\') 1272 synerror("Bad escape sequence"); 1273 if (c == '?') 1274 v = 127; 1275 else 1276 v = c & 0x1f; 1277 break; 1278 case 'u': 1279 case 'U': 1280 n = c == 'U' ? 8 : 4; 1281 v = 0; 1282 for (i = 0; i < n; i++) { 1283 c = pgetc(); 1284 if (c >= '0' && c <= '9') 1285 v = (v << 4) + c - '0'; 1286 else if (c >= 'A' && c <= 'F') 1287 v = (v << 4) + c - 'A' + 10; 1288 else if (c >= 'a' && c <= 'f') 1289 v = (v << 4) + c - 'a' + 10; 1290 else 1291 synerror("Bad escape sequence"); 1292 } 1293 if (v == 0 || (v >= 0xd800 && v <= 0xdfff)) 1294 synerror("Bad escape sequence"); 1295 /* We really need iconv here. */ 1296 if (initial_localeisutf8 && v > 127) { 1297 CHECKSTRSPACE(4, out); 1298 /* 1299 * We cannot use wctomb() as the locale may have 1300 * changed. 1301 */ 1302 if (v <= 0x7ff) { 1303 USTPUTC(0xc0 | v >> 6, out); 1304 USTPUTC(0x80 | (v & 0x3f), out); 1305 return out; 1306 } else if (v <= 0xffff) { 1307 USTPUTC(0xe0 | v >> 12, out); 1308 USTPUTC(0x80 | ((v >> 6) & 0x3f), out); 1309 USTPUTC(0x80 | (v & 0x3f), out); 1310 return out; 1311 } else if (v <= 0x10ffff) { 1312 USTPUTC(0xf0 | v >> 18, out); 1313 USTPUTC(0x80 | ((v >> 12) & 0x3f), out); 1314 USTPUTC(0x80 | ((v >> 6) & 0x3f), out); 1315 USTPUTC(0x80 | (v & 0x3f), out); 1316 return out; 1317 } 1318 } 1319 if (v > 127) 1320 v = '?'; 1321 break; 1322 default: 1323 synerror("Bad escape sequence"); 1324 } 1325 v = (char)v; 1326 /* 1327 * We can't handle NUL bytes. 1328 * POSIX says we should skip till the closing quote. 1329 */ 1330 if (v == '\0') { 1331 while ((c = pgetc()) != '\'') { 1332 if (c == '\\') 1333 c = pgetc(); 1334 if (c == PEOF) 1335 synerror("Unterminated quoted string"); 1336 if (c == '\n') { 1337 plinno++; 1338 if (doprompt) 1339 setprompt(2); 1340 else 1341 setprompt(0); 1342 } 1343 } 1344 pungetc(); 1345 return out; 1346 } 1347 if (SQSYNTAX[v] == CCTL) 1348 USTPUTC(CTLESC, out); 1349 USTPUTC(v, out); 1350 return out; 1351 } 1352 1353 1354 /* 1355 * If eofmark is NULL, read a word or a redirection symbol. If eofmark 1356 * is not NULL, read a here document. In the latter case, eofmark is the 1357 * word which marks the end of the document and striptabs is true if 1358 * leading tabs should be stripped from the document. The argument firstc 1359 * is the first character of the input token or document. 1360 * 1361 * Because C does not have internal subroutines, I have simulated them 1362 * using goto's to implement the subroutine linkage. The following macros 1363 * will run code that appears at the end of readtoken1. 1364 */ 1365 1366 #define PARSESUB() {goto parsesub; parsesub_return:;} 1367 #define PARSEARITH() {goto parsearith; parsearith_return:;} 1368 1369 static int 1370 readtoken1(int firstc, char const *initialsyntax, const char *eofmark, 1371 int striptabs) 1372 { 1373 int c = firstc; 1374 char *out; 1375 int len; 1376 struct nodelist *bqlist; 1377 int quotef; 1378 int newvarnest; 1379 int level; 1380 int synentry; 1381 struct tokenstate state_static[MAXNEST_static]; 1382 int maxnest = MAXNEST_static; 1383 struct tokenstate *state = state_static; 1384 int sqiscstyle = 0; 1385 1386 startlinno = plinno; 1387 quotef = 0; 1388 bqlist = NULL; 1389 newvarnest = 0; 1390 level = 0; 1391 state[level].syntax = initialsyntax; 1392 state[level].parenlevel = 0; 1393 state[level].category = TSTATE_TOP; 1394 1395 STARTSTACKSTR(out); 1396 loop: { /* for each line, until end of word */ 1397 if (eofmark) 1398 /* set c to PEOF if at end of here document */ 1399 c = checkend(c, eofmark, striptabs); 1400 for (;;) { /* until end of line or end of word */ 1401 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */ 1402 1403 synentry = state[level].syntax[c]; 1404 1405 switch(synentry) { 1406 case CNL: /* '\n' */ 1407 if (state[level].syntax == BASESYNTAX) 1408 goto endword; /* exit outer loop */ 1409 USTPUTC(c, out); 1410 plinno++; 1411 if (doprompt) 1412 setprompt(2); 1413 else 1414 setprompt(0); 1415 c = pgetc(); 1416 goto loop; /* continue outer loop */ 1417 case CSBACK: 1418 if (sqiscstyle) { 1419 out = readcstyleesc(out); 1420 break; 1421 } 1422 /* FALLTHROUGH */ 1423 case CWORD: 1424 USTPUTC(c, out); 1425 break; 1426 case CCTL: 1427 if (eofmark == NULL || initialsyntax != SQSYNTAX) 1428 USTPUTC(CTLESC, out); 1429 USTPUTC(c, out); 1430 break; 1431 case CBACK: /* backslash */ 1432 c = pgetc(); 1433 if (c == PEOF) { 1434 USTPUTC('\\', out); 1435 pungetc(); 1436 } else if (c == '\n') { 1437 plinno++; 1438 if (doprompt) 1439 setprompt(2); 1440 else 1441 setprompt(0); 1442 } else { 1443 if (state[level].syntax == DQSYNTAX && 1444 c != '\\' && c != '`' && c != '$' && 1445 (c != '"' || (eofmark != NULL && 1446 newvarnest == 0)) && 1447 (c != '}' || state[level].category != TSTATE_VAR_OLD)) 1448 USTPUTC('\\', out); 1449 if ((eofmark == NULL || 1450 newvarnest > 0) && 1451 state[level].syntax == BASESYNTAX) 1452 USTPUTC(CTLQUOTEMARK, out); 1453 if (SQSYNTAX[c] == CCTL) 1454 USTPUTC(CTLESC, out); 1455 USTPUTC(c, out); 1456 if ((eofmark == NULL || 1457 newvarnest > 0) && 1458 state[level].syntax == BASESYNTAX && 1459 state[level].category == TSTATE_VAR_OLD) 1460 USTPUTC(CTLQUOTEEND, out); 1461 quotef++; 1462 } 1463 break; 1464 case CSQUOTE: 1465 USTPUTC(CTLQUOTEMARK, out); 1466 state[level].syntax = SQSYNTAX; 1467 sqiscstyle = 0; 1468 break; 1469 case CDQUOTE: 1470 USTPUTC(CTLQUOTEMARK, out); 1471 state[level].syntax = DQSYNTAX; 1472 break; 1473 case CENDQUOTE: 1474 if (eofmark != NULL && newvarnest == 0) 1475 USTPUTC(c, out); 1476 else { 1477 if (state[level].category == TSTATE_VAR_OLD) 1478 USTPUTC(CTLQUOTEEND, out); 1479 state[level].syntax = BASESYNTAX; 1480 quotef++; 1481 } 1482 break; 1483 case CVAR: /* '$' */ 1484 PARSESUB(); /* parse substitution */ 1485 break; 1486 case CENDVAR: /* '}' */ 1487 if (level > 0 && 1488 ((state[level].category == TSTATE_VAR_OLD && 1489 state[level].syntax == 1490 state[level - 1].syntax) || 1491 (state[level].category == TSTATE_VAR_NEW && 1492 state[level].syntax == BASESYNTAX))) { 1493 if (state[level].category == TSTATE_VAR_NEW) 1494 newvarnest--; 1495 level--; 1496 USTPUTC(CTLENDVAR, out); 1497 } else { 1498 USTPUTC(c, out); 1499 } 1500 break; 1501 case CLP: /* '(' in arithmetic */ 1502 state[level].parenlevel++; 1503 USTPUTC(c, out); 1504 break; 1505 case CRP: /* ')' in arithmetic */ 1506 if (state[level].parenlevel > 0) { 1507 USTPUTC(c, out); 1508 --state[level].parenlevel; 1509 } else { 1510 if (pgetc() == ')') { 1511 if (level > 0 && 1512 state[level].category == TSTATE_ARITH) { 1513 level--; 1514 USTPUTC(CTLENDARI, out); 1515 } else 1516 USTPUTC(')', out); 1517 } else { 1518 /* 1519 * unbalanced parens 1520 * (don't 2nd guess - no error) 1521 */ 1522 pungetc(); 1523 USTPUTC(')', out); 1524 } 1525 } 1526 break; 1527 case CBQUOTE: /* '`' */ 1528 out = parsebackq(out, &bqlist, 1, 1529 state[level].syntax == DQSYNTAX && 1530 (eofmark == NULL || newvarnest > 0), 1531 state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX); 1532 break; 1533 case CEOF: 1534 goto endword; /* exit outer loop */ 1535 case CIGN: 1536 break; 1537 default: 1538 if (level == 0) 1539 goto endword; /* exit outer loop */ 1540 USTPUTC(c, out); 1541 } 1542 c = pgetc_macro(); 1543 } 1544 } 1545 endword: 1546 if (state[level].syntax == ARISYNTAX) 1547 synerror("Missing '))'"); 1548 if (state[level].syntax != BASESYNTAX && eofmark == NULL) 1549 synerror("Unterminated quoted string"); 1550 if (state[level].category == TSTATE_VAR_OLD || 1551 state[level].category == TSTATE_VAR_NEW) { 1552 startlinno = plinno; 1553 synerror("Missing '}'"); 1554 } 1555 if (state != state_static) 1556 parser_temp_free_upto(state); 1557 USTPUTC('\0', out); 1558 len = out - stackblock(); 1559 out = stackblock(); 1560 if (eofmark == NULL) { 1561 if ((c == '>' || c == '<') 1562 && quotef == 0 1563 && len <= 2 1564 && (*out == '\0' || is_digit(*out))) { 1565 parseredir(out, c); 1566 return lasttoken = TREDIR; 1567 } else { 1568 pungetc(); 1569 } 1570 } 1571 quoteflag = quotef; 1572 backquotelist = bqlist; 1573 grabstackblock(len); 1574 wordtext = out; 1575 return lasttoken = TWORD; 1576 /* end of readtoken routine */ 1577 1578 1579 /* 1580 * Parse a substitution. At this point, we have read the dollar sign 1581 * and nothing else. 1582 */ 1583 1584 parsesub: { 1585 char buf[10]; 1586 int subtype; 1587 int typeloc; 1588 int flags; 1589 char *p; 1590 static const char types[] = "}-+?="; 1591 int bracketed_name = 0; /* used to handle ${[0-9]*} variables */ 1592 int linno; 1593 int length; 1594 int c1; 1595 1596 c = pgetc(); 1597 if (c == '(') { /* $(command) or $((arith)) */ 1598 if (pgetc() == '(') { 1599 PARSEARITH(); 1600 } else { 1601 pungetc(); 1602 out = parsebackq(out, &bqlist, 0, 1603 state[level].syntax == DQSYNTAX && 1604 (eofmark == NULL || newvarnest > 0), 1605 state[level].syntax == DQSYNTAX || 1606 state[level].syntax == ARISYNTAX); 1607 } 1608 } else if (c == '{' || is_name(c) || is_special(c)) { 1609 USTPUTC(CTLVAR, out); 1610 typeloc = out - stackblock(); 1611 USTPUTC(VSNORMAL, out); 1612 subtype = VSNORMAL; 1613 flags = 0; 1614 if (c == '{') { 1615 bracketed_name = 1; 1616 c = pgetc(); 1617 subtype = 0; 1618 } 1619 varname: 1620 if (!is_eof(c) && is_name(c)) { 1621 length = 0; 1622 do { 1623 STPUTC(c, out); 1624 c = pgetc(); 1625 length++; 1626 } while (!is_eof(c) && is_in_name(c)); 1627 if (length == 6 && 1628 strncmp(out - length, "LINENO", length) == 0) { 1629 /* Replace the variable name with the 1630 * current line number. */ 1631 linno = plinno; 1632 if (funclinno != 0) 1633 linno -= funclinno - 1; 1634 snprintf(buf, sizeof(buf), "%d", linno); 1635 STADJUST(-6, out); 1636 STPUTS(buf, out); 1637 flags |= VSLINENO; 1638 } 1639 } else if (is_digit(c)) { 1640 if (bracketed_name) { 1641 do { 1642 STPUTC(c, out); 1643 c = pgetc(); 1644 } while (is_digit(c)); 1645 } else { 1646 STPUTC(c, out); 1647 c = pgetc(); 1648 } 1649 } else if (is_special(c)) { 1650 c1 = c; 1651 c = pgetc(); 1652 if (subtype == 0 && c1 == '#') { 1653 subtype = VSLENGTH; 1654 if (strchr(types, c) == NULL && c != ':' && 1655 c != '#' && c != '%') 1656 goto varname; 1657 c1 = c; 1658 c = pgetc(); 1659 if (c1 != '}' && c == '}') { 1660 pungetc(); 1661 c = c1; 1662 goto varname; 1663 } 1664 pungetc(); 1665 c = c1; 1666 c1 = '#'; 1667 subtype = 0; 1668 } 1669 USTPUTC(c1, out); 1670 } else { 1671 subtype = VSERROR; 1672 if (c == '}') 1673 pungetc(); 1674 else if (c == '\n' || c == PEOF) 1675 synerror("Unexpected end of line in substitution"); 1676 else 1677 USTPUTC(c, out); 1678 } 1679 if (subtype == 0) { 1680 switch (c) { 1681 case ':': 1682 flags |= VSNUL; 1683 c = pgetc(); 1684 /*FALLTHROUGH*/ 1685 default: 1686 p = strchr(types, c); 1687 if (p == NULL) { 1688 if (c == '\n' || c == PEOF) 1689 synerror("Unexpected end of line in substitution"); 1690 if (flags == VSNUL) 1691 STPUTC(':', out); 1692 STPUTC(c, out); 1693 subtype = VSERROR; 1694 } else 1695 subtype = p - types + VSNORMAL; 1696 break; 1697 case '%': 1698 case '#': 1699 { 1700 int cc = c; 1701 subtype = c == '#' ? VSTRIMLEFT : 1702 VSTRIMRIGHT; 1703 c = pgetc(); 1704 if (c == cc) 1705 subtype++; 1706 else 1707 pungetc(); 1708 break; 1709 } 1710 } 1711 } else if (subtype != VSERROR) { 1712 if (subtype == VSLENGTH && c != '}') 1713 subtype = VSERROR; 1714 pungetc(); 1715 } 1716 STPUTC('=', out); 1717 if (state[level].syntax == DQSYNTAX || 1718 state[level].syntax == ARISYNTAX) 1719 flags |= VSQUOTE; 1720 *(stackblock() + typeloc) = subtype | flags; 1721 if (subtype != VSNORMAL) { 1722 if (level + 1 >= maxnest) { 1723 maxnest *= 2; 1724 if (state == state_static) { 1725 state = parser_temp_alloc( 1726 maxnest * sizeof(*state)); 1727 memcpy(state, state_static, 1728 MAXNEST_static * sizeof(*state)); 1729 } else 1730 state = parser_temp_realloc(state, 1731 maxnest * sizeof(*state)); 1732 } 1733 level++; 1734 state[level].parenlevel = 0; 1735 if (subtype == VSMINUS || subtype == VSPLUS || 1736 subtype == VSQUESTION || subtype == VSASSIGN) { 1737 /* 1738 * For operators that were in the Bourne shell, 1739 * inherit the double-quote state. 1740 */ 1741 state[level].syntax = state[level - 1].syntax; 1742 state[level].category = TSTATE_VAR_OLD; 1743 } else { 1744 /* 1745 * The other operators take a pattern, 1746 * so go to BASESYNTAX. 1747 * Also, ' and " are now special, even 1748 * in here documents. 1749 */ 1750 state[level].syntax = BASESYNTAX; 1751 state[level].category = TSTATE_VAR_NEW; 1752 newvarnest++; 1753 } 1754 } 1755 } else if (c == '\'' && state[level].syntax == BASESYNTAX) { 1756 /* $'cstylequotes' */ 1757 USTPUTC(CTLQUOTEMARK, out); 1758 state[level].syntax = SQSYNTAX; 1759 sqiscstyle = 1; 1760 } else { 1761 USTPUTC('$', out); 1762 pungetc(); 1763 } 1764 goto parsesub_return; 1765 } 1766 1767 1768 /* 1769 * Parse an arithmetic expansion (indicate start of one and set state) 1770 */ 1771 parsearith: { 1772 1773 if (level + 1 >= maxnest) { 1774 maxnest *= 2; 1775 if (state == state_static) { 1776 state = parser_temp_alloc( 1777 maxnest * sizeof(*state)); 1778 memcpy(state, state_static, 1779 MAXNEST_static * sizeof(*state)); 1780 } else 1781 state = parser_temp_realloc(state, 1782 maxnest * sizeof(*state)); 1783 } 1784 level++; 1785 state[level].syntax = ARISYNTAX; 1786 state[level].parenlevel = 0; 1787 state[level].category = TSTATE_ARITH; 1788 USTPUTC(CTLARI, out); 1789 if (state[level - 1].syntax == DQSYNTAX) 1790 USTPUTC('"',out); 1791 else 1792 USTPUTC(' ',out); 1793 goto parsearith_return; 1794 } 1795 1796 } /* end of readtoken */ 1797 1798 1799 /* 1800 * Returns true if the text contains nothing to expand (no dollar signs 1801 * or backquotes). 1802 */ 1803 1804 static int 1805 noexpand(char *text) 1806 { 1807 char *p; 1808 char c; 1809 1810 p = text; 1811 while ((c = *p++) != '\0') { 1812 if ( c == CTLQUOTEMARK) 1813 continue; 1814 if (c == CTLESC) 1815 p++; 1816 else if (BASESYNTAX[(int)c] == CCTL) 1817 return 0; 1818 } 1819 return 1; 1820 } 1821 1822 1823 /* 1824 * Return true if the argument is a legal variable name (a letter or 1825 * underscore followed by zero or more letters, underscores, and digits). 1826 */ 1827 1828 int 1829 goodname(const char *name) 1830 { 1831 const char *p; 1832 1833 p = name; 1834 if (! is_name(*p)) 1835 return 0; 1836 while (*++p) { 1837 if (! is_in_name(*p)) 1838 return 0; 1839 } 1840 return 1; 1841 } 1842 1843 1844 int 1845 isassignment(const char *p) 1846 { 1847 if (!is_name(*p)) 1848 return 0; 1849 p++; 1850 for (;;) { 1851 if (*p == '=') 1852 return 1; 1853 else if (!is_in_name(*p)) 1854 return 0; 1855 p++; 1856 } 1857 } 1858 1859 1860 static void 1861 consumetoken(int token) 1862 { 1863 if (readtoken() != token) 1864 synexpect(token); 1865 } 1866 1867 1868 /* 1869 * Called when an unexpected token is read during the parse. The argument 1870 * is the token that is expected, or -1 if more than one type of token can 1871 * occur at this point. 1872 */ 1873 1874 static void 1875 synexpect(int token) 1876 { 1877 char msg[64]; 1878 1879 if (token >= 0) { 1880 fmtstr(msg, 64, "%s unexpected (expecting %s)", 1881 tokname[lasttoken], tokname[token]); 1882 } else { 1883 fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]); 1884 } 1885 synerror(msg); 1886 } 1887 1888 1889 static void 1890 synerror(const char *msg) 1891 { 1892 if (commandname) 1893 outfmt(out2, "%s: %d: ", commandname, startlinno); 1894 outfmt(out2, "Syntax error: %s\n", msg); 1895 error((char *)NULL); 1896 } 1897 1898 static void 1899 setprompt(int which) 1900 { 1901 whichprompt = which; 1902 1903 #ifndef NO_HISTORY 1904 if (!el) 1905 #endif 1906 { 1907 out2str(getprompt(NULL)); 1908 flushout(out2); 1909 } 1910 } 1911 1912 /* 1913 * called by editline -- any expansions to the prompt 1914 * should be added here. 1915 */ 1916 char * 1917 getprompt(void *unused __unused) 1918 { 1919 static char ps[PROMPTLEN]; 1920 const char *fmt; 1921 const char *pwd; 1922 int i, trim; 1923 static char internal_error[] = "??"; 1924 1925 /* 1926 * Select prompt format. 1927 */ 1928 switch (whichprompt) { 1929 case 0: 1930 fmt = nullstr; 1931 break; 1932 case 1: 1933 fmt = ps1val(); 1934 break; 1935 case 2: 1936 fmt = ps2val(); 1937 break; 1938 default: 1939 return internal_error; 1940 } 1941 1942 /* 1943 * Format prompt string. 1944 */ 1945 for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++) 1946 if (*fmt == '\\') 1947 switch (*++fmt) { 1948 1949 /* 1950 * Hostname. 1951 * 1952 * \h specifies just the local hostname, 1953 * \H specifies fully-qualified hostname. 1954 */ 1955 case 'h': 1956 case 'H': 1957 ps[i] = '\0'; 1958 gethostname(&ps[i], PROMPTLEN - i); 1959 /* Skip to end of hostname. */ 1960 trim = (*fmt == 'h') ? '.' : '\0'; 1961 while ((ps[i+1] != '\0') && (ps[i+1] != trim)) 1962 i++; 1963 break; 1964 1965 /* 1966 * Working directory. 1967 * 1968 * \W specifies just the final component, 1969 * \w specifies the entire path. 1970 */ 1971 case 'W': 1972 case 'w': 1973 pwd = lookupvar("PWD"); 1974 if (pwd == NULL) 1975 pwd = "?"; 1976 if (*fmt == 'W' && 1977 *pwd == '/' && pwd[1] != '\0') 1978 strlcpy(&ps[i], strrchr(pwd, '/') + 1, 1979 PROMPTLEN - i); 1980 else 1981 strlcpy(&ps[i], pwd, PROMPTLEN - i); 1982 /* Skip to end of path. */ 1983 while (ps[i + 1] != '\0') 1984 i++; 1985 break; 1986 1987 /* 1988 * Superuser status. 1989 * 1990 * '$' for normal users, '#' for root. 1991 */ 1992 case '$': 1993 ps[i] = (geteuid() != 0) ? '$' : '#'; 1994 break; 1995 1996 /* 1997 * A literal \. 1998 */ 1999 case '\\': 2000 ps[i] = '\\'; 2001 break; 2002 2003 /* 2004 * Emit unrecognized formats verbatim. 2005 */ 2006 default: 2007 ps[i++] = '\\'; 2008 ps[i] = *fmt; 2009 break; 2010 } 2011 else 2012 ps[i] = *fmt; 2013 ps[i] = '\0'; 2014 return (ps); 2015 } 2016 2017 2018 const char * 2019 expandstr(const char *ps) 2020 { 2021 union node n; 2022 struct jmploc jmploc; 2023 struct jmploc *const savehandler = handler; 2024 const int saveprompt = doprompt; 2025 struct parsefile *const savetopfile = getcurrentfile(); 2026 struct parser_temp *const saveparser_temp = parser_temp; 2027 const char *result = NULL; 2028 2029 if (!setjmp(jmploc.loc)) { 2030 handler = &jmploc; 2031 parser_temp = NULL; 2032 setinputstring(ps, 1); 2033 doprompt = 0; 2034 readtoken1(pgetc(), DQSYNTAX, "", 0); 2035 if (backquotelist != NULL) 2036 error("Command substitution not allowed here"); 2037 2038 n.narg.type = NARG; 2039 n.narg.next = NULL; 2040 n.narg.text = wordtext; 2041 n.narg.backquote = backquotelist; 2042 2043 expandarg(&n, NULL, 0); 2044 result = stackblock(); 2045 INTOFF; 2046 } 2047 handler = savehandler; 2048 doprompt = saveprompt; 2049 popfilesupto(savetopfile); 2050 if (parser_temp != saveparser_temp) { 2051 parser_temp_free_all(); 2052 parser_temp = saveparser_temp; 2053 } 2054 if (result != NULL) { 2055 INTON; 2056 } else if (exception == EXINT) 2057 raise(SIGINT); 2058 return result; 2059 } 2060