1 /*- 2 * Copyright (c) 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[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95"; 36 #endif 37 #endif /* not lint */ 38 #include <sys/cdefs.h> 39 __FBSDID("$FreeBSD$"); 40 41 #include <paths.h> 42 #include <signal.h> 43 #include <stdlib.h> 44 #include <unistd.h> 45 #include <sys/resource.h> 46 #include <sys/wait.h> /* For WIFSIGNALED(status) */ 47 #include <errno.h> 48 49 /* 50 * Evaluate a command. 51 */ 52 53 #include "shell.h" 54 #include "nodes.h" 55 #include "syntax.h" 56 #include "expand.h" 57 #include "parser.h" 58 #include "jobs.h" 59 #include "eval.h" 60 #include "builtins.h" 61 #include "options.h" 62 #include "exec.h" 63 #include "redir.h" 64 #include "input.h" 65 #include "output.h" 66 #include "trap.h" 67 #include "var.h" 68 #include "memalloc.h" 69 #include "error.h" 70 #include "show.h" 71 #include "mystring.h" 72 #ifndef NO_HISTORY 73 #include "myhistedit.h" 74 #endif 75 76 77 int evalskip; /* set if we are skipping commands */ 78 int skipcount; /* number of levels to skip */ 79 MKINIT int loopnest; /* current loop nesting level */ 80 int funcnest; /* depth of function calls */ 81 static int builtin_flags; /* evalcommand flags for builtins */ 82 83 84 char *commandname; 85 struct strlist *cmdenviron; 86 int exitstatus; /* exit status of last command */ 87 int oexitstatus; /* saved exit status */ 88 89 90 static void evalloop(union node *, int); 91 static void evalfor(union node *, int); 92 static union node *evalcase(union node *); 93 static void evalsubshell(union node *, int); 94 static void evalredir(union node *, int); 95 static void exphere(union node *, struct arglist *); 96 static void expredir(union node *); 97 static void evalpipe(union node *); 98 static int is_valid_fast_cmdsubst(union node *n); 99 static void evalcommand(union node *, int, struct backcmd *); 100 static void prehash(union node *); 101 102 103 /* 104 * Called to reset things after an exception. 105 */ 106 107 #ifdef mkinit 108 INCLUDE "eval.h" 109 110 RESET { 111 evalskip = 0; 112 loopnest = 0; 113 funcnest = 0; 114 } 115 #endif 116 117 118 119 /* 120 * The eval command. 121 */ 122 123 int 124 evalcmd(int argc, char **argv) 125 { 126 char *p; 127 char *concat; 128 char **ap; 129 130 if (argc > 1) { 131 p = argv[1]; 132 if (argc > 2) { 133 STARTSTACKSTR(concat); 134 ap = argv + 2; 135 for (;;) { 136 STPUTS(p, concat); 137 if ((p = *ap++) == NULL) 138 break; 139 STPUTC(' ', concat); 140 } 141 STPUTC('\0', concat); 142 p = grabstackstr(concat); 143 } 144 evalstring(p, builtin_flags); 145 } else 146 exitstatus = 0; 147 return exitstatus; 148 } 149 150 151 /* 152 * Execute a command or commands contained in a string. 153 */ 154 155 void 156 evalstring(char *s, int flags) 157 { 158 union node *n; 159 struct stackmark smark; 160 int flags_exit; 161 int any; 162 163 flags_exit = flags & EV_EXIT; 164 flags &= ~EV_EXIT; 165 any = 0; 166 setstackmark(&smark); 167 setinputstring(s, 1); 168 while ((n = parsecmd(0)) != NEOF) { 169 if (n != NULL && !nflag) { 170 if (flags_exit && preadateof()) 171 evaltree(n, flags | EV_EXIT); 172 else 173 evaltree(n, flags); 174 any = 1; 175 } 176 popstackmark(&smark); 177 setstackmark(&smark); 178 } 179 popfile(); 180 popstackmark(&smark); 181 if (!any) 182 exitstatus = 0; 183 if (flags_exit) 184 exraise(EXEXIT); 185 } 186 187 188 /* 189 * Evaluate a parse tree. The value is left in the global variable 190 * exitstatus. 191 */ 192 193 void 194 evaltree(union node *n, int flags) 195 { 196 int do_etest; 197 union node *next; 198 struct stackmark smark; 199 200 setstackmark(&smark); 201 do_etest = 0; 202 if (n == NULL) { 203 TRACE(("evaltree(NULL) called\n")); 204 exitstatus = 0; 205 goto out; 206 } 207 do { 208 next = NULL; 209 #ifndef NO_HISTORY 210 displayhist = 1; /* show history substitutions done with fc */ 211 #endif 212 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type)); 213 switch (n->type) { 214 case NSEMI: 215 evaltree(n->nbinary.ch1, flags & ~EV_EXIT); 216 if (evalskip) 217 goto out; 218 next = n->nbinary.ch2; 219 break; 220 case NAND: 221 evaltree(n->nbinary.ch1, EV_TESTED); 222 if (evalskip || exitstatus != 0) { 223 goto out; 224 } 225 next = n->nbinary.ch2; 226 break; 227 case NOR: 228 evaltree(n->nbinary.ch1, EV_TESTED); 229 if (evalskip || exitstatus == 0) 230 goto out; 231 next = n->nbinary.ch2; 232 break; 233 case NREDIR: 234 evalredir(n, flags); 235 break; 236 case NSUBSHELL: 237 evalsubshell(n, flags); 238 do_etest = !(flags & EV_TESTED); 239 break; 240 case NBACKGND: 241 evalsubshell(n, flags); 242 break; 243 case NIF: { 244 evaltree(n->nif.test, EV_TESTED); 245 if (evalskip) 246 goto out; 247 if (exitstatus == 0) 248 next = n->nif.ifpart; 249 else if (n->nif.elsepart) 250 next = n->nif.elsepart; 251 else 252 exitstatus = 0; 253 break; 254 } 255 case NWHILE: 256 case NUNTIL: 257 evalloop(n, flags & ~EV_EXIT); 258 break; 259 case NFOR: 260 evalfor(n, flags & ~EV_EXIT); 261 break; 262 case NCASE: 263 next = evalcase(n); 264 break; 265 case NCLIST: 266 next = n->nclist.body; 267 break; 268 case NCLISTFALLTHRU: 269 if (n->nclist.body) { 270 evaltree(n->nclist.body, flags & ~EV_EXIT); 271 if (evalskip) 272 goto out; 273 } 274 next = n->nclist.next; 275 break; 276 case NDEFUN: 277 defun(n->narg.text, n->narg.next); 278 exitstatus = 0; 279 break; 280 case NNOT: 281 evaltree(n->nnot.com, EV_TESTED); 282 if (evalskip) 283 goto out; 284 exitstatus = !exitstatus; 285 break; 286 287 case NPIPE: 288 evalpipe(n); 289 do_etest = !(flags & EV_TESTED); 290 break; 291 case NCMD: 292 evalcommand(n, flags, (struct backcmd *)NULL); 293 do_etest = !(flags & EV_TESTED); 294 break; 295 default: 296 out1fmt("Node type = %d\n", n->type); 297 flushout(&output); 298 break; 299 } 300 n = next; 301 popstackmark(&smark); 302 setstackmark(&smark); 303 } while (n != NULL); 304 out: 305 popstackmark(&smark); 306 if (pendingsig) 307 dotrap(); 308 if (eflag && exitstatus != 0 && do_etest) 309 exitshell(exitstatus); 310 if (flags & EV_EXIT) 311 exraise(EXEXIT); 312 } 313 314 315 static void 316 evalloop(union node *n, int flags) 317 { 318 int status; 319 320 loopnest++; 321 status = 0; 322 for (;;) { 323 evaltree(n->nbinary.ch1, EV_TESTED); 324 if (evalskip) { 325 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { 326 evalskip = 0; 327 continue; 328 } 329 if (evalskip == SKIPBREAK && --skipcount <= 0) 330 evalskip = 0; 331 if (evalskip == SKIPFUNC || evalskip == SKIPFILE) 332 status = exitstatus; 333 break; 334 } 335 if (n->type == NWHILE) { 336 if (exitstatus != 0) 337 break; 338 } else { 339 if (exitstatus == 0) 340 break; 341 } 342 evaltree(n->nbinary.ch2, flags); 343 status = exitstatus; 344 if (evalskip) 345 goto skipping; 346 } 347 loopnest--; 348 exitstatus = status; 349 } 350 351 352 353 static void 354 evalfor(union node *n, int flags) 355 { 356 struct arglist arglist; 357 union node *argp; 358 struct strlist *sp; 359 int status; 360 361 arglist.lastp = &arglist.list; 362 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { 363 oexitstatus = exitstatus; 364 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 365 } 366 *arglist.lastp = NULL; 367 368 loopnest++; 369 status = 0; 370 for (sp = arglist.list ; sp ; sp = sp->next) { 371 setvar(n->nfor.var, sp->text, 0); 372 evaltree(n->nfor.body, flags); 373 status = exitstatus; 374 if (evalskip) { 375 if (evalskip == SKIPCONT && --skipcount <= 0) { 376 evalskip = 0; 377 continue; 378 } 379 if (evalskip == SKIPBREAK && --skipcount <= 0) 380 evalskip = 0; 381 break; 382 } 383 } 384 loopnest--; 385 exitstatus = status; 386 } 387 388 389 /* 390 * Evaluate a case statement, returning the selected tree. 391 * 392 * The exit status needs care to get right. 393 */ 394 395 static union node * 396 evalcase(union node *n) 397 { 398 union node *cp; 399 union node *patp; 400 struct arglist arglist; 401 402 arglist.lastp = &arglist.list; 403 oexitstatus = exitstatus; 404 expandarg(n->ncase.expr, &arglist, EXP_TILDE); 405 for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) { 406 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) { 407 if (casematch(patp, arglist.list->text)) { 408 while (cp->nclist.next && 409 cp->type == NCLISTFALLTHRU && 410 cp->nclist.body == NULL) 411 cp = cp->nclist.next; 412 if (cp->nclist.next && 413 cp->type == NCLISTFALLTHRU) 414 return (cp); 415 if (cp->nclist.body == NULL) 416 exitstatus = 0; 417 return (cp->nclist.body); 418 } 419 } 420 } 421 exitstatus = 0; 422 return (NULL); 423 } 424 425 426 427 /* 428 * Kick off a subshell to evaluate a tree. 429 */ 430 431 static void 432 evalsubshell(union node *n, int flags) 433 { 434 struct job *jp; 435 int backgnd = (n->type == NBACKGND); 436 437 oexitstatus = exitstatus; 438 expredir(n->nredir.redirect); 439 if ((!backgnd && flags & EV_EXIT && !have_traps()) || 440 forkshell(jp = makejob(n, 1), n, backgnd) == 0) { 441 if (backgnd) 442 flags &=~ EV_TESTED; 443 redirect(n->nredir.redirect, 0); 444 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */ 445 } else if (! backgnd) { 446 INTOFF; 447 exitstatus = waitforjob(jp, (int *)NULL); 448 INTON; 449 } else 450 exitstatus = 0; 451 } 452 453 454 /* 455 * Evaluate a redirected compound command. 456 */ 457 458 static void 459 evalredir(union node *n, int flags) 460 { 461 struct jmploc jmploc; 462 struct jmploc *savehandler; 463 volatile int in_redirect = 1; 464 465 oexitstatus = exitstatus; 466 expredir(n->nredir.redirect); 467 savehandler = handler; 468 if (setjmp(jmploc.loc)) { 469 int e; 470 471 handler = savehandler; 472 e = exception; 473 popredir(); 474 if (e == EXERROR || e == EXEXEC) { 475 if (in_redirect) { 476 exitstatus = 2; 477 return; 478 } 479 } 480 longjmp(handler->loc, 1); 481 } else { 482 INTOFF; 483 handler = &jmploc; 484 redirect(n->nredir.redirect, REDIR_PUSH); 485 in_redirect = 0; 486 INTON; 487 evaltree(n->nredir.n, flags); 488 } 489 INTOFF; 490 handler = savehandler; 491 popredir(); 492 INTON; 493 } 494 495 496 static void 497 exphere(union node *redir, struct arglist *fn) 498 { 499 struct jmploc jmploc; 500 struct jmploc *savehandler; 501 struct localvar *savelocalvars; 502 int need_longjmp = 0; 503 504 redir->nhere.expdoc = nullstr; 505 savelocalvars = localvars; 506 localvars = NULL; 507 forcelocal++; 508 savehandler = handler; 509 if (setjmp(jmploc.loc)) 510 need_longjmp = exception != EXERROR && exception != EXEXEC; 511 else { 512 handler = &jmploc; 513 expandarg(redir->nhere.doc, fn, 0); 514 redir->nhere.expdoc = fn->list->text; 515 INTOFF; 516 } 517 handler = savehandler; 518 forcelocal--; 519 poplocalvars(); 520 localvars = savelocalvars; 521 if (need_longjmp) 522 longjmp(handler->loc, 1); 523 INTON; 524 } 525 526 527 /* 528 * Compute the names of the files in a redirection list. 529 */ 530 531 static void 532 expredir(union node *n) 533 { 534 union node *redir; 535 536 for (redir = n ; redir ; redir = redir->nfile.next) { 537 struct arglist fn; 538 fn.lastp = &fn.list; 539 switch (redir->type) { 540 case NFROM: 541 case NTO: 542 case NFROMTO: 543 case NAPPEND: 544 case NCLOBBER: 545 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR); 546 redir->nfile.expfname = fn.list->text; 547 break; 548 case NFROMFD: 549 case NTOFD: 550 if (redir->ndup.vname) { 551 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR); 552 fixredir(redir, fn.list->text, 1); 553 } 554 break; 555 case NXHERE: 556 exphere(redir, &fn); 557 break; 558 } 559 } 560 } 561 562 563 564 /* 565 * Evaluate a pipeline. All the processes in the pipeline are children 566 * of the process creating the pipeline. (This differs from some versions 567 * of the shell, which make the last process in a pipeline the parent 568 * of all the rest.) 569 */ 570 571 static void 572 evalpipe(union node *n) 573 { 574 struct job *jp; 575 struct nodelist *lp; 576 int pipelen; 577 int prevfd; 578 int pip[2]; 579 580 TRACE(("evalpipe(%p) called\n", (void *)n)); 581 pipelen = 0; 582 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) 583 pipelen++; 584 INTOFF; 585 jp = makejob(n, pipelen); 586 prevfd = -1; 587 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) { 588 prehash(lp->n); 589 pip[1] = -1; 590 if (lp->next) { 591 if (pipe(pip) < 0) { 592 close(prevfd); 593 error("Pipe call failed: %s", strerror(errno)); 594 } 595 } 596 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) { 597 INTON; 598 if (prevfd > 0) { 599 dup2(prevfd, 0); 600 close(prevfd); 601 } 602 if (pip[1] >= 0) { 603 if (!(prevfd >= 0 && pip[0] == 0)) 604 close(pip[0]); 605 if (pip[1] != 1) { 606 dup2(pip[1], 1); 607 close(pip[1]); 608 } 609 } 610 evaltree(lp->n, EV_EXIT); 611 } 612 if (prevfd >= 0) 613 close(prevfd); 614 prevfd = pip[0]; 615 if (pip[1] != -1) 616 close(pip[1]); 617 } 618 INTON; 619 if (n->npipe.backgnd == 0) { 620 INTOFF; 621 exitstatus = waitforjob(jp, (int *)NULL); 622 TRACE(("evalpipe: job done exit status %d\n", exitstatus)); 623 INTON; 624 } else 625 exitstatus = 0; 626 } 627 628 629 630 static int 631 is_valid_fast_cmdsubst(union node *n) 632 { 633 634 return (n->type == NCMD); 635 } 636 637 /* 638 * Execute a command inside back quotes. If it's a builtin command, we 639 * want to save its output in a block obtained from malloc. Otherwise 640 * we fork off a subprocess and get the output of the command via a pipe. 641 * Should be called with interrupts off. 642 */ 643 644 void 645 evalbackcmd(union node *n, struct backcmd *result) 646 { 647 int pip[2]; 648 struct job *jp; 649 struct stackmark smark; 650 struct jmploc jmploc; 651 struct jmploc *savehandler; 652 struct localvar *savelocalvars; 653 654 setstackmark(&smark); 655 result->fd = -1; 656 result->buf = NULL; 657 result->nleft = 0; 658 result->jp = NULL; 659 if (n == NULL) { 660 exitstatus = 0; 661 goto out; 662 } 663 exitstatus = oexitstatus; 664 if (is_valid_fast_cmdsubst(n)) { 665 savelocalvars = localvars; 666 localvars = NULL; 667 forcelocal++; 668 savehandler = handler; 669 if (setjmp(jmploc.loc)) { 670 if (exception == EXERROR || exception == EXEXEC) 671 exitstatus = 2; 672 else if (exception != 0) { 673 handler = savehandler; 674 forcelocal--; 675 poplocalvars(); 676 localvars = savelocalvars; 677 longjmp(handler->loc, 1); 678 } 679 } else { 680 handler = &jmploc; 681 evalcommand(n, EV_BACKCMD, result); 682 } 683 handler = savehandler; 684 forcelocal--; 685 poplocalvars(); 686 localvars = savelocalvars; 687 } else { 688 if (pipe(pip) < 0) 689 error("Pipe call failed: %s", strerror(errno)); 690 jp = makejob(n, 1); 691 if (forkshell(jp, n, FORK_NOJOB) == 0) { 692 FORCEINTON; 693 close(pip[0]); 694 if (pip[1] != 1) { 695 dup2(pip[1], 1); 696 close(pip[1]); 697 } 698 evaltree(n, EV_EXIT); 699 } 700 close(pip[1]); 701 result->fd = pip[0]; 702 result->jp = jp; 703 } 704 out: 705 popstackmark(&smark); 706 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n", 707 result->fd, result->buf, result->nleft, result->jp)); 708 } 709 710 static int 711 mustexpandto(const char *argtext, const char *mask) 712 { 713 for (;;) { 714 if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) { 715 argtext++; 716 continue; 717 } 718 if (*argtext == CTLESC) 719 argtext++; 720 else if (BASESYNTAX[(int)*argtext] == CCTL) 721 return (0); 722 if (*argtext != *mask) 723 return (0); 724 if (*argtext == '\0') 725 return (1); 726 argtext++; 727 mask++; 728 } 729 } 730 731 static int 732 isdeclarationcmd(struct narg *arg) 733 { 734 int have_command = 0; 735 736 if (arg == NULL) 737 return (0); 738 while (mustexpandto(arg->text, "command")) { 739 have_command = 1; 740 arg = &arg->next->narg; 741 if (arg == NULL) 742 return (0); 743 /* 744 * To also allow "command -p" and "command --" as part of 745 * a declaration command, add code here. 746 * We do not do this, as ksh does not do it either and it 747 * is not required by POSIX. 748 */ 749 } 750 return (mustexpandto(arg->text, "export") || 751 mustexpandto(arg->text, "readonly") || 752 (mustexpandto(arg->text, "local") && 753 (have_command || !isfunc("local")))); 754 } 755 756 /* 757 * Check if a builtin can safely be executed in the same process, 758 * even though it should be in a subshell (command substitution). 759 * Note that jobid, jobs, times and trap can show information not 760 * available in a child process; this is deliberate. 761 * The arguments should already have been expanded. 762 */ 763 static int 764 safe_builtin(int idx, int argc, char **argv) 765 { 766 if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD || 767 idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD || 768 idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD || 769 idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD || 770 idx == TYPECMD) 771 return (1); 772 if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || 773 idx == UMASKCMD) 774 return (argc <= 1 || (argc == 2 && argv[1][0] == '-')); 775 if (idx == SETCMD) 776 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' || 777 argv[1][0] == '+') && argv[1][1] == 'o' && 778 argv[1][2] == '\0')); 779 return (0); 780 } 781 782 /* 783 * Execute a simple command. 784 * Note: This may or may not return if (flags & EV_EXIT). 785 */ 786 787 static void 788 evalcommand(union node *cmd, int flags, struct backcmd *backcmd) 789 { 790 union node *argp; 791 struct arglist arglist; 792 struct arglist varlist; 793 char **argv; 794 int argc; 795 char **envp; 796 int varflag; 797 struct strlist *sp; 798 int mode; 799 int pip[2]; 800 struct cmdentry cmdentry; 801 struct job *jp; 802 struct jmploc jmploc; 803 struct jmploc *savehandler; 804 char *savecmdname; 805 struct shparam saveparam; 806 struct localvar *savelocalvars; 807 struct parsefile *savetopfile; 808 volatile int e; 809 char *lastarg; 810 int realstatus; 811 int do_clearcmdentry; 812 const char *path = pathval(); 813 814 /* First expand the arguments. */ 815 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags)); 816 arglist.lastp = &arglist.list; 817 varlist.lastp = &varlist.list; 818 varflag = 1; 819 jp = NULL; 820 do_clearcmdentry = 0; 821 oexitstatus = exitstatus; 822 exitstatus = 0; 823 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { 824 if (varflag && isassignment(argp->narg.text)) { 825 expandarg(argp, varflag == 1 ? &varlist : &arglist, 826 EXP_VARTILDE); 827 continue; 828 } else if (varflag == 1) 829 varflag = isdeclarationcmd(&argp->narg) ? 2 : 0; 830 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 831 } 832 *arglist.lastp = NULL; 833 *varlist.lastp = NULL; 834 expredir(cmd->ncmd.redirect); 835 argc = 0; 836 for (sp = arglist.list ; sp ; sp = sp->next) 837 argc++; 838 /* Add one slot at the beginning for tryexec(). */ 839 argv = stalloc(sizeof (char *) * (argc + 2)); 840 argv++; 841 842 for (sp = arglist.list ; sp ; sp = sp->next) { 843 TRACE(("evalcommand arg: %s\n", sp->text)); 844 *argv++ = sp->text; 845 } 846 *argv = NULL; 847 lastarg = NULL; 848 if (iflag && funcnest == 0 && argc > 0) 849 lastarg = argv[-1]; 850 argv -= argc; 851 852 /* Print the command if xflag is set. */ 853 if (xflag) { 854 char sep = 0; 855 const char *p, *ps4; 856 ps4 = expandstr(ps4val()); 857 out2str(ps4 != NULL ? ps4 : ps4val()); 858 for (sp = varlist.list ; sp ; sp = sp->next) { 859 if (sep != 0) 860 out2c(' '); 861 p = strchr(sp->text, '='); 862 if (p != NULL) { 863 p++; 864 outbin(sp->text, p - sp->text, out2); 865 out2qstr(p); 866 } else 867 out2qstr(sp->text); 868 sep = ' '; 869 } 870 for (sp = arglist.list ; sp ; sp = sp->next) { 871 if (sep != 0) 872 out2c(' '); 873 /* Disambiguate command looking like assignment. */ 874 if (sp == arglist.list && 875 strchr(sp->text, '=') != NULL && 876 strchr(sp->text, '\'') == NULL) { 877 out2c('\''); 878 out2str(sp->text); 879 out2c('\''); 880 } else 881 out2qstr(sp->text); 882 sep = ' '; 883 } 884 out2c('\n'); 885 flushout(&errout); 886 } 887 888 /* Now locate the command. */ 889 if (argc == 0) { 890 /* Variable assignment(s) without command */ 891 cmdentry.cmdtype = CMDBUILTIN; 892 cmdentry.u.index = BLTINCMD; 893 cmdentry.special = 0; 894 } else { 895 static const char PATH[] = "PATH="; 896 int cmd_flags = 0, bltinonly = 0; 897 898 /* 899 * Modify the command lookup path, if a PATH= assignment 900 * is present 901 */ 902 for (sp = varlist.list ; sp ; sp = sp->next) 903 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) { 904 path = sp->text + sizeof(PATH) - 1; 905 /* 906 * On `PATH=... command`, we need to make 907 * sure that the command isn't using the 908 * non-updated hash table of the outer PATH 909 * setting and we need to make sure that 910 * the hash table isn't filled with items 911 * from the temporary setting. 912 * 913 * It would be better to forbit using and 914 * updating the table while this command 915 * runs, by the command finding mechanism 916 * is heavily integrated with hash handling, 917 * so we just delete the hash before and after 918 * the command runs. Partly deleting like 919 * changepatch() does doesn't seem worth the 920 * bookinging effort, since most such runs add 921 * directories in front of the new PATH. 922 */ 923 clearcmdentry(); 924 do_clearcmdentry = 1; 925 } 926 927 for (;;) { 928 if (bltinonly) { 929 cmdentry.u.index = find_builtin(*argv, &cmdentry.special); 930 if (cmdentry.u.index < 0) { 931 cmdentry.u.index = BLTINCMD; 932 argv--; 933 argc++; 934 break; 935 } 936 } else 937 find_command(argv[0], &cmdentry, cmd_flags, path); 938 /* implement the bltin and command builtins here */ 939 if (cmdentry.cmdtype != CMDBUILTIN) 940 break; 941 if (cmdentry.u.index == BLTINCMD) { 942 if (argc == 1) 943 break; 944 argv++; 945 argc--; 946 bltinonly = 1; 947 } else if (cmdentry.u.index == COMMANDCMD) { 948 if (argc == 1) 949 break; 950 if (!strcmp(argv[1], "-p")) { 951 if (argc == 2) 952 break; 953 if (argv[2][0] == '-') { 954 if (strcmp(argv[2], "--")) 955 break; 956 if (argc == 3) 957 break; 958 argv += 3; 959 argc -= 3; 960 } else { 961 argv += 2; 962 argc -= 2; 963 } 964 path = _PATH_STDPATH; 965 clearcmdentry(); 966 do_clearcmdentry = 1; 967 } else if (!strcmp(argv[1], "--")) { 968 if (argc == 2) 969 break; 970 argv += 2; 971 argc -= 2; 972 } else if (argv[1][0] == '-') 973 break; 974 else { 975 argv++; 976 argc--; 977 } 978 cmd_flags |= DO_NOFUNC; 979 bltinonly = 0; 980 } else 981 break; 982 } 983 /* 984 * Special builtins lose their special properties when 985 * called via 'command'. 986 */ 987 if (cmd_flags & DO_NOFUNC) 988 cmdentry.special = 0; 989 } 990 991 /* Fork off a child process if necessary. */ 992 if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN) 993 && ((flags & EV_EXIT) == 0 || have_traps())) 994 || ((flags & EV_BACKCMD) != 0 995 && (cmdentry.cmdtype != CMDBUILTIN || 996 !safe_builtin(cmdentry.u.index, argc, argv)))) { 997 jp = makejob(cmd, 1); 998 mode = FORK_FG; 999 if (flags & EV_BACKCMD) { 1000 mode = FORK_NOJOB; 1001 if (pipe(pip) < 0) 1002 error("Pipe call failed: %s", strerror(errno)); 1003 } 1004 if (cmdentry.cmdtype == CMDNORMAL && 1005 cmd->ncmd.redirect == NULL && 1006 varlist.list == NULL && 1007 (mode == FORK_FG || mode == FORK_NOJOB) && 1008 !disvforkset() && !iflag && !mflag) { 1009 vforkexecshell(jp, argv, environment(), path, 1010 cmdentry.u.index, flags & EV_BACKCMD ? pip : NULL); 1011 goto parent; 1012 } 1013 if (forkshell(jp, cmd, mode) != 0) 1014 goto parent; /* at end of routine */ 1015 if (flags & EV_BACKCMD) { 1016 FORCEINTON; 1017 close(pip[0]); 1018 if (pip[1] != 1) { 1019 dup2(pip[1], 1); 1020 close(pip[1]); 1021 } 1022 flags &= ~EV_BACKCMD; 1023 } 1024 flags |= EV_EXIT; 1025 } 1026 1027 /* This is the child process if a fork occurred. */ 1028 /* Execute the command. */ 1029 if (cmdentry.cmdtype == CMDFUNCTION) { 1030 #ifdef DEBUG 1031 trputs("Shell function: "); trargs(argv); 1032 #endif 1033 saveparam = shellparam; 1034 shellparam.malloc = 0; 1035 shellparam.reset = 1; 1036 shellparam.nparam = argc - 1; 1037 shellparam.p = argv + 1; 1038 shellparam.optnext = NULL; 1039 INTOFF; 1040 savelocalvars = localvars; 1041 localvars = NULL; 1042 reffunc(cmdentry.u.func); 1043 savehandler = handler; 1044 if (setjmp(jmploc.loc)) { 1045 freeparam(&shellparam); 1046 shellparam = saveparam; 1047 popredir(); 1048 unreffunc(cmdentry.u.func); 1049 poplocalvars(); 1050 localvars = savelocalvars; 1051 funcnest--; 1052 handler = savehandler; 1053 longjmp(handler->loc, 1); 1054 } 1055 handler = &jmploc; 1056 funcnest++; 1057 redirect(cmd->ncmd.redirect, REDIR_PUSH); 1058 INTON; 1059 for (sp = varlist.list ; sp ; sp = sp->next) 1060 mklocal(sp->text); 1061 exitstatus = oexitstatus; 1062 evaltree(getfuncnode(cmdentry.u.func), 1063 flags & (EV_TESTED | EV_EXIT)); 1064 INTOFF; 1065 unreffunc(cmdentry.u.func); 1066 poplocalvars(); 1067 localvars = savelocalvars; 1068 freeparam(&shellparam); 1069 shellparam = saveparam; 1070 handler = savehandler; 1071 funcnest--; 1072 popredir(); 1073 INTON; 1074 if (evalskip == SKIPFUNC) { 1075 evalskip = 0; 1076 skipcount = 0; 1077 } 1078 if (jp) 1079 exitshell(exitstatus); 1080 } else if (cmdentry.cmdtype == CMDBUILTIN) { 1081 #ifdef DEBUG 1082 trputs("builtin command: "); trargs(argv); 1083 #endif 1084 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH; 1085 if (flags == EV_BACKCMD) { 1086 memout.nleft = 0; 1087 memout.nextc = memout.buf; 1088 memout.bufsize = 64; 1089 mode |= REDIR_BACKQ; 1090 } 1091 savecmdname = commandname; 1092 savetopfile = getcurrentfile(); 1093 cmdenviron = varlist.list; 1094 e = -1; 1095 savehandler = handler; 1096 if (setjmp(jmploc.loc)) { 1097 e = exception; 1098 if (e == EXINT) 1099 exitstatus = SIGINT+128; 1100 else if (e != EXEXIT) 1101 exitstatus = 2; 1102 goto cmddone; 1103 } 1104 handler = &jmploc; 1105 redirect(cmd->ncmd.redirect, mode); 1106 outclearerror(out1); 1107 /* 1108 * If there is no command word, redirection errors should 1109 * not be fatal but assignment errors should. 1110 */ 1111 if (argc == 0) 1112 cmdentry.special = 1; 1113 listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET); 1114 if (argc > 0) 1115 bltinsetlocale(); 1116 commandname = argv[0]; 1117 argptr = argv + 1; 1118 nextopt_optptr = NULL; /* initialize nextopt */ 1119 builtin_flags = flags; 1120 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv); 1121 flushall(); 1122 if (outiserror(out1)) { 1123 warning("write error on stdout"); 1124 if (exitstatus == 0 || exitstatus == 1) 1125 exitstatus = 2; 1126 } 1127 cmddone: 1128 if (argc > 0) 1129 bltinunsetlocale(); 1130 cmdenviron = NULL; 1131 out1 = &output; 1132 out2 = &errout; 1133 freestdout(); 1134 handler = savehandler; 1135 commandname = savecmdname; 1136 if (jp) 1137 exitshell(exitstatus); 1138 if (flags == EV_BACKCMD) { 1139 backcmd->buf = memout.buf; 1140 backcmd->nleft = memout.nextc - memout.buf; 1141 memout.buf = NULL; 1142 } 1143 if (cmdentry.u.index != EXECCMD) 1144 popredir(); 1145 if (e != -1) { 1146 if ((e != EXERROR && e != EXEXEC) 1147 || cmdentry.special) 1148 exraise(e); 1149 popfilesupto(savetopfile); 1150 if (flags != EV_BACKCMD) 1151 FORCEINTON; 1152 } 1153 } else { 1154 #ifdef DEBUG 1155 trputs("normal command: "); trargs(argv); 1156 #endif 1157 redirect(cmd->ncmd.redirect, 0); 1158 for (sp = varlist.list ; sp ; sp = sp->next) 1159 setvareq(sp->text, VEXPORT|VSTACK); 1160 envp = environment(); 1161 shellexec(argv, envp, path, cmdentry.u.index); 1162 /*NOTREACHED*/ 1163 } 1164 goto out; 1165 1166 parent: /* parent process gets here (if we forked) */ 1167 if (mode == FORK_FG) { /* argument to fork */ 1168 INTOFF; 1169 exitstatus = waitforjob(jp, &realstatus); 1170 INTON; 1171 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) { 1172 evalskip = SKIPBREAK; 1173 skipcount = loopnest; 1174 } 1175 } else if (mode == FORK_NOJOB) { 1176 backcmd->fd = pip[0]; 1177 close(pip[1]); 1178 backcmd->jp = jp; 1179 } 1180 1181 out: 1182 if (lastarg) 1183 setvar("_", lastarg, 0); 1184 if (do_clearcmdentry) 1185 clearcmdentry(); 1186 } 1187 1188 1189 1190 /* 1191 * Search for a command. This is called before we fork so that the 1192 * location of the command will be available in the parent as well as 1193 * the child. The check for "goodname" is an overly conservative 1194 * check that the name will not be subject to expansion. 1195 */ 1196 1197 static void 1198 prehash(union node *n) 1199 { 1200 struct cmdentry entry; 1201 1202 if (n && n->type == NCMD && n->ncmd.args) 1203 if (goodname(n->ncmd.args->narg.text)) 1204 find_command(n->ncmd.args->narg.text, &entry, 0, 1205 pathval()); 1206 } 1207 1208 1209 1210 /* 1211 * Builtin commands. Builtin commands whose functions are closely 1212 * tied to evaluation are implemented here. 1213 */ 1214 1215 /* 1216 * No command given, a bltin command with no arguments, or a bltin command 1217 * with an invalid name. 1218 */ 1219 1220 int 1221 bltincmd(int argc, char **argv) 1222 { 1223 if (argc > 1) { 1224 out2fmt_flush("%s: not found\n", argv[1]); 1225 return 127; 1226 } 1227 /* 1228 * Preserve exitstatus of a previous possible redirection 1229 * as POSIX mandates 1230 */ 1231 return exitstatus; 1232 } 1233 1234 1235 /* 1236 * Handle break and continue commands. Break, continue, and return are 1237 * all handled by setting the evalskip flag. The evaluation routines 1238 * above all check this flag, and if it is set they start skipping 1239 * commands rather than executing them. The variable skipcount is 1240 * the number of loops to break/continue, or the number of function 1241 * levels to return. (The latter is always 1.) It should probably 1242 * be an error to break out of more loops than exist, but it isn't 1243 * in the standard shell so we don't make it one here. 1244 */ 1245 1246 int 1247 breakcmd(int argc, char **argv) 1248 { 1249 int n = argc > 1 ? number(argv[1]) : 1; 1250 1251 if (n > loopnest) 1252 n = loopnest; 1253 if (n > 0) { 1254 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK; 1255 skipcount = n; 1256 } 1257 return 0; 1258 } 1259 1260 /* 1261 * The `command' command. 1262 */ 1263 int 1264 commandcmd(int argc __unused, char **argv __unused) 1265 { 1266 const char *path; 1267 int ch; 1268 int cmd = -1; 1269 1270 path = bltinlookup("PATH", 1); 1271 1272 while ((ch = nextopt("pvV")) != '\0') { 1273 switch (ch) { 1274 case 'p': 1275 path = _PATH_STDPATH; 1276 break; 1277 case 'v': 1278 cmd = TYPECMD_SMALLV; 1279 break; 1280 case 'V': 1281 cmd = TYPECMD_BIGV; 1282 break; 1283 } 1284 } 1285 1286 if (cmd != -1) { 1287 if (*argptr == NULL || argptr[1] != NULL) 1288 error("wrong number of arguments"); 1289 return typecmd_impl(2, argptr - 1, cmd, path); 1290 } 1291 if (*argptr != NULL) 1292 error("commandcmd bad call"); 1293 1294 /* 1295 * Do nothing successfully if no command was specified; 1296 * ksh also does this. 1297 */ 1298 return 0; 1299 } 1300 1301 1302 /* 1303 * The return command. 1304 */ 1305 1306 int 1307 returncmd(int argc, char **argv) 1308 { 1309 int ret = argc > 1 ? number(argv[1]) : oexitstatus; 1310 1311 if (funcnest) { 1312 evalskip = SKIPFUNC; 1313 skipcount = 1; 1314 } else { 1315 /* skip the rest of the file */ 1316 evalskip = SKIPFILE; 1317 skipcount = 1; 1318 } 1319 return ret; 1320 } 1321 1322 1323 int 1324 falsecmd(int argc __unused, char **argv __unused) 1325 { 1326 return 1; 1327 } 1328 1329 1330 int 1331 truecmd(int argc __unused, char **argv __unused) 1332 { 1333 return 0; 1334 } 1335 1336 1337 int 1338 execcmd(int argc, char **argv) 1339 { 1340 /* 1341 * Because we have historically not supported any options, 1342 * only treat "--" specially. 1343 */ 1344 if (argc > 1 && strcmp(argv[1], "--") == 0) 1345 argc--, argv++; 1346 if (argc > 1) { 1347 struct strlist *sp; 1348 1349 iflag = 0; /* exit on error */ 1350 mflag = 0; 1351 optschanged(); 1352 for (sp = cmdenviron; sp ; sp = sp->next) 1353 setvareq(sp->text, VEXPORT|VSTACK); 1354 shellexec(argv + 1, environment(), pathval(), 0); 1355 1356 } 1357 return 0; 1358 } 1359 1360 1361 int 1362 timescmd(int argc __unused, char **argv __unused) 1363 { 1364 struct rusage ru; 1365 long shumins, shsmins, chumins, chsmins; 1366 double shusecs, shssecs, chusecs, chssecs; 1367 1368 if (getrusage(RUSAGE_SELF, &ru) < 0) 1369 return 1; 1370 shumins = ru.ru_utime.tv_sec / 60; 1371 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1372 shsmins = ru.ru_stime.tv_sec / 60; 1373 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1374 if (getrusage(RUSAGE_CHILDREN, &ru) < 0) 1375 return 1; 1376 chumins = ru.ru_utime.tv_sec / 60; 1377 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1378 chsmins = ru.ru_stime.tv_sec / 60; 1379 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1380 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins, 1381 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs); 1382 return 0; 1383 } 1384