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