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