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 * 3. All advertising materials mentioning features or use of this software 17 * must display the following acknowledgement: 18 * This product includes software developed by the University of 19 * California, Berkeley and its contributors. 20 * 4. Neither the name of the University nor the names of its contributors 21 * may be used to endorse or promote products derived from this software 22 * without specific prior written permission. 23 * 24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 34 * SUCH DAMAGE. 35 * 36 * @(#)eval.c 8.9 (Berkeley) 6/8/95 37 * $FreeBSD: src/bin/sh/eval.c,v 1.102 2011/04/23 22:28:56 jilles Exp $ 38 */ 39 40 #include <sys/time.h> 41 #include <sys/resource.h> 42 #include <sys/wait.h> /* For WIFSIGNALED(status) */ 43 44 #include <errno.h> 45 #include <paths.h> 46 #include <signal.h> 47 #include <stdlib.h> 48 #include <unistd.h> 49 50 /* 51 * Evaluate a command. 52 */ 53 54 #include "shell.h" 55 #include "nodes.h" 56 #include "syntax.h" 57 #include "expand.h" 58 #include "parser.h" 59 #include "jobs.h" 60 #include "eval.h" 61 #include "builtins.h" 62 #include "options.h" 63 #include "exec.h" 64 #include "redir.h" 65 #include "input.h" 66 #include "output.h" 67 #include "trap.h" 68 #include "var.h" 69 #include "memalloc.h" 70 #include "error.h" 71 #include "show.h" 72 #include "mystring.h" 73 #ifndef NO_HISTORY 74 #include "myhistedit.h" 75 #endif 76 77 78 int evalskip; /* set if we are skipping commands */ 79 static int skipcount; /* number of levels to skip */ 80 MKINIT int loopnest; /* current loop nesting level */ 81 int funcnest; /* depth of function calls */ 82 static int builtin_flags; /* evalcommand flags for builtins */ 83 84 85 const char *commandname; 86 struct strlist *cmdenviron; 87 int exitstatus; /* exit status of last command */ 88 int oexitstatus; /* saved exit status */ 89 90 91 static void evalloop(union node *, int); 92 static void evalfor(union node *, int); 93 static void evalcase(union node *, int); 94 static void evalsubshell(union node *, int); 95 static void evalredir(union node *, int); 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 & EV_TESTED); 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) { 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 } 178 popfile(); 179 popstackmark(&smark); 180 if (!any) 181 exitstatus = 0; 182 if (flags_exit) 183 exraise(EXEXIT); 184 } 185 186 187 /* 188 * Evaluate a parse tree. The value is left in the global variable 189 * exitstatus. 190 */ 191 192 void 193 evaltree(union node *n, int flags) 194 { 195 int do_etest; 196 union node *next; 197 198 do_etest = 0; 199 if (n == NULL) { 200 TRACE(("evaltree(NULL) called\n")); 201 exitstatus = 0; 202 goto out; 203 } 204 do { 205 next = NULL; 206 #ifndef NO_HISTORY 207 displayhist = 1; /* show history substitutions done with fc */ 208 #endif 209 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type)); 210 switch (n->type) { 211 case NSEMI: 212 evaltree(n->nbinary.ch1, flags & ~EV_EXIT); 213 if (evalskip) 214 goto out; 215 next = n->nbinary.ch2; 216 break; 217 case NAND: 218 evaltree(n->nbinary.ch1, EV_TESTED); 219 if (evalskip || exitstatus != 0) { 220 goto out; 221 } 222 next = n->nbinary.ch2; 223 break; 224 case NOR: 225 evaltree(n->nbinary.ch1, EV_TESTED); 226 if (evalskip || exitstatus == 0) 227 goto out; 228 next = n->nbinary.ch2; 229 break; 230 case NREDIR: 231 evalredir(n, flags); 232 break; 233 case NSUBSHELL: 234 evalsubshell(n, flags); 235 do_etest = !(flags & EV_TESTED); 236 break; 237 case NBACKGND: 238 evalsubshell(n, flags); 239 break; 240 case NIF: { 241 evaltree(n->nif.test, EV_TESTED); 242 if (evalskip) 243 goto out; 244 if (exitstatus == 0) 245 next = n->nif.ifpart; 246 else if (n->nif.elsepart) 247 next = n->nif.elsepart; 248 else 249 exitstatus = 0; 250 break; 251 } 252 case NWHILE: 253 case NUNTIL: 254 evalloop(n, flags & ~EV_EXIT); 255 break; 256 case NFOR: 257 evalfor(n, flags & ~EV_EXIT); 258 break; 259 case NCASE: 260 evalcase(n, flags); 261 break; 262 case NDEFUN: 263 defun(n->narg.text, n->narg.next); 264 exitstatus = 0; 265 break; 266 case NNOT: 267 evaltree(n->nnot.com, EV_TESTED); 268 exitstatus = !exitstatus; 269 break; 270 271 case NPIPE: 272 evalpipe(n); 273 do_etest = !(flags & EV_TESTED); 274 break; 275 case NCMD: 276 evalcommand(n, flags, NULL); 277 do_etest = !(flags & EV_TESTED); 278 break; 279 default: 280 out1fmt("Node type = %d\n", n->type); 281 flushout(&output); 282 break; 283 } 284 n = next; 285 } while (n != NULL); 286 out: 287 if (pendingsigs) 288 dotrap(); 289 if (eflag && exitstatus != 0 && do_etest) 290 exitshell(exitstatus); 291 if (flags & EV_EXIT) 292 exraise(EXEXIT); 293 } 294 295 296 static void 297 evalloop(union node *n, int flags) 298 { 299 int status; 300 301 loopnest++; 302 status = 0; 303 for (;;) { 304 evaltree(n->nbinary.ch1, EV_TESTED); 305 if (evalskip) { 306 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { 307 evalskip = 0; 308 continue; 309 } 310 if (evalskip == SKIPBREAK && --skipcount <= 0) 311 evalskip = 0; 312 if (evalskip == SKIPFUNC || evalskip == SKIPFILE) 313 status = exitstatus; 314 break; 315 } 316 if (n->type == NWHILE) { 317 if (exitstatus != 0) 318 break; 319 } else { 320 if (exitstatus == 0) 321 break; 322 } 323 evaltree(n->nbinary.ch2, flags); 324 status = exitstatus; 325 if (evalskip) 326 goto skipping; 327 } 328 loopnest--; 329 exitstatus = status; 330 } 331 332 333 334 static void 335 evalfor(union node *n, int flags) 336 { 337 struct arglist arglist; 338 union node *argp; 339 struct strlist *sp; 340 struct stackmark smark; 341 342 setstackmark(&smark); 343 arglist.lastp = &arglist.list; 344 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { 345 oexitstatus = exitstatus; 346 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 347 if (evalskip) 348 goto out; 349 } 350 *arglist.lastp = NULL; 351 352 exitstatus = 0; 353 loopnest++; 354 for (sp = arglist.list ; sp ; sp = sp->next) { 355 setvar(n->nfor.var, sp->text, 0); 356 evaltree(n->nfor.body, flags); 357 if (evalskip) { 358 if (evalskip == SKIPCONT && --skipcount <= 0) { 359 evalskip = 0; 360 continue; 361 } 362 if (evalskip == SKIPBREAK && --skipcount <= 0) 363 evalskip = 0; 364 break; 365 } 366 } 367 loopnest--; 368 out: 369 popstackmark(&smark); 370 } 371 372 373 374 static void 375 evalcase(union node *n, int flags) 376 { 377 union node *cp; 378 union node *patp; 379 struct arglist arglist; 380 struct stackmark smark; 381 382 setstackmark(&smark); 383 arglist.lastp = &arglist.list; 384 oexitstatus = exitstatus; 385 exitstatus = 0; 386 expandarg(n->ncase.expr, &arglist, EXP_TILDE); 387 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) { 388 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) { 389 if (casematch(patp, arglist.list->text)) { 390 if (evalskip == 0) { 391 evaltree(cp->nclist.body, flags); 392 } 393 goto out; 394 } 395 } 396 } 397 out: 398 popstackmark(&smark); 399 } 400 401 402 403 /* 404 * Kick off a subshell to evaluate a tree. 405 */ 406 407 static void 408 evalsubshell(union node *n, int flags) 409 { 410 struct job *jp; 411 int backgnd = (n->type == NBACKGND); 412 413 expredir(n->nredir.redirect); 414 if ((!backgnd && flags & EV_EXIT && !have_traps()) || 415 forkshell(jp = makejob(n, 1), n, backgnd) == 0) { 416 if (backgnd) 417 flags &=~ EV_TESTED; 418 redirect(n->nredir.redirect, 0); 419 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */ 420 } else if (!backgnd) { 421 INTOFF; 422 exitstatus = waitforjob(jp, NULL); 423 INTON; 424 } 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 if (prevfd >= 0) 533 close(prevfd); 534 error("Pipe call failed: %s", strerror(errno)); 535 } 536 } 537 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) { 538 INTON; 539 if (prevfd > 0) { 540 dup2(prevfd, 0); 541 close(prevfd); 542 } 543 if (pip[1] >= 0) { 544 if (!(prevfd >= 0 && pip[0] == 0)) 545 close(pip[0]); 546 if (pip[1] != 1) { 547 dup2(pip[1], 1); 548 close(pip[1]); 549 } 550 } 551 evaltree(lp->n, EV_EXIT); 552 } 553 if (prevfd >= 0) 554 close(prevfd); 555 prevfd = pip[0]; 556 close(pip[1]); 557 } 558 INTON; 559 if (n->npipe.backgnd == 0) { 560 INTOFF; 561 exitstatus = waitforjob(jp, NULL); 562 TRACE(("evalpipe: job done exit status %d\n", exitstatus)); 563 INTON; 564 } 565 } 566 567 568 569 static int 570 is_valid_fast_cmdsubst(union node *n) 571 { 572 union node *argp; 573 574 if (n->type != NCMD) 575 return 0; 576 for (argp = n->ncmd.args ; argp ; argp = argp->narg.next) 577 if (expandhassideeffects(argp->narg.text)) 578 return 0; 579 return 1; 580 } 581 582 /* 583 * Execute a command inside back quotes. If it's a builtin command, we 584 * want to save its output in a block obtained from malloc. Otherwise 585 * we fork off a subprocess and get the output of the command via a pipe. 586 * Should be called with interrupts off. 587 */ 588 589 void 590 evalbackcmd(union node *n, struct backcmd *result) 591 { 592 int pip[2]; 593 struct job *jp; 594 struct stackmark smark; /* unnecessary */ 595 struct jmploc jmploc; 596 struct jmploc *savehandler; 597 598 setstackmark(&smark); 599 result->fd = -1; 600 result->buf = NULL; 601 result->nleft = 0; 602 result->jp = NULL; 603 if (n == NULL) { 604 exitstatus = 0; 605 goto out; 606 } 607 if (is_valid_fast_cmdsubst(n)) { 608 exitstatus = oexitstatus; 609 savehandler = handler; 610 if (setjmp(jmploc.loc)) { 611 if (exception == EXERROR || exception == EXEXEC) 612 exitstatus = 2; 613 else if (exception != 0) { 614 handler = savehandler; 615 longjmp(handler->loc, 1); 616 } 617 } else { 618 handler = &jmploc; 619 evalcommand(n, EV_BACKCMD, result); 620 } 621 handler = savehandler; 622 } else { 623 exitstatus = 0; 624 if (pipe(pip) < 0) 625 error("Pipe call failed: %s", strerror(errno)); 626 jp = makejob(n, 1); 627 if (forkshell(jp, n, FORK_NOJOB) == 0) { 628 FORCEINTON; 629 close(pip[0]); 630 if (pip[1] != 1) { 631 dup2(pip[1], 1); 632 close(pip[1]); 633 } 634 evaltree(n, EV_EXIT); 635 } 636 close(pip[1]); 637 result->fd = pip[0]; 638 result->jp = jp; 639 } 640 out: 641 popstackmark(&smark); 642 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n", 643 result->fd, result->buf, result->nleft, result->jp)); 644 } 645 646 /* 647 * Check if a builtin can safely be executed in the same process, 648 * even though it should be in a subshell (command substitution). 649 * Note that jobid, jobs, times and trap can show information not 650 * available in a child process; this is deliberate. 651 * The arguments should already have been expanded. 652 */ 653 static int 654 safe_builtin(int idx, int argc, char **argv) 655 { 656 if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD || 657 idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD || 658 idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD || 659 idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD || 660 idx == TYPECMD) 661 return (1); 662 if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || 663 idx == UMASKCMD) 664 return (argc <= 1 || (argc == 2 && argv[1][0] == '-')); 665 if (idx == SETCMD) 666 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' || 667 argv[1][0] == '+') && argv[1][1] == 'o' && 668 argv[1][2] == '\0')); 669 return (0); 670 } 671 672 /* 673 * Execute a simple command. 674 * Note: This may or may not return if (flags & EV_EXIT). 675 */ 676 677 static void 678 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd) 679 { 680 struct stackmark smark; 681 union node *argp; 682 struct arglist arglist; 683 struct arglist varlist; 684 volatile int flags = flgs; 685 char **volatile argv; 686 volatile 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 *volatile jp; 694 struct jmploc jmploc; 695 struct jmploc *savehandler; 696 const char *savecmdname; 697 struct shparam saveparam; 698 struct localvar *savelocalvars; 699 struct parsefile *savetopfile; 700 volatile int e; 701 char *volatile lastarg; 702 int realstatus; 703 volatile 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 char *p = argp->narg.text; 718 if (varflag && is_name(*p)) { 719 do { 720 p++; 721 } while (is_in_name(*p)); 722 if (*p == '=') { 723 expandarg(argp, &varlist, EXP_VARTILDE); 724 continue; 725 } 726 } 727 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 728 varflag = 0; 729 } 730 *arglist.lastp = NULL; 731 *varlist.lastp = NULL; 732 expredir(cmd->ncmd.redirect); 733 argc = 0; 734 for (sp = arglist.list ; sp ; sp = sp->next) 735 argc++; 736 /* Add one slot at the beginning for tryexec(). */ 737 argv = stalloc(sizeof (char *) * (argc + 2)); 738 argv++; 739 740 for (sp = arglist.list ; sp ; sp = sp->next) { 741 TRACE(("evalcommand arg: %s\n", sp->text)); 742 *argv++ = sp->text; 743 } 744 *argv = NULL; 745 lastarg = NULL; 746 if (iflag && funcnest == 0 && argc > 0) 747 lastarg = argv[-1]; 748 argv -= argc; 749 750 /* Print the command if xflag is set. */ 751 if (xflag) { 752 char sep = 0; 753 const char *p; 754 out2str(ps4val()); 755 for (sp = varlist.list ; sp ; sp = sp->next) { 756 if (sep != 0) 757 out2c(' '); 758 p = strchr(sp->text, '='); 759 if (p != NULL) { 760 p++; 761 outbin(sp->text, p - sp->text, out2); 762 out2qstr(p); 763 } else 764 out2qstr(sp->text); 765 sep = ' '; 766 } 767 for (sp = arglist.list ; sp ; sp = sp->next) { 768 if (sep != 0) 769 out2c(' '); 770 /* Disambiguate command looking like assignment. */ 771 if (sp == arglist.list && 772 strchr(sp->text, '=') != NULL && 773 strchr(sp->text, '\'') == NULL) { 774 out2c('\''); 775 out2str(sp->text); 776 out2c('\''); 777 } else 778 out2qstr(sp->text); 779 sep = ' '; 780 } 781 out2c('\n'); 782 flushout(&errout); 783 } 784 785 /* Now locate the command. */ 786 if (argc == 0) { 787 /* Variable assignment(s) without command */ 788 cmdentry.cmdtype = CMDBUILTIN; 789 cmdentry.u.index = BLTINCMD; 790 cmdentry.special = 0; 791 } else { 792 static const char PATH[] = "PATH="; 793 int cmd_flags = 0, bltinonly = 0; 794 795 /* 796 * Modify the command lookup path, if a PATH= assignment 797 * is present 798 */ 799 for (sp = varlist.list ; sp ; sp = sp->next) 800 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) { 801 path = sp->text + sizeof(PATH) - 1; 802 /* 803 * On `PATH=... command`, we need to make 804 * sure that the command isn't using the 805 * non-updated hash table of the outer PATH 806 * setting and we need to make sure that 807 * the hash table isn't filled with items 808 * from the temporary setting. 809 * 810 * It would be better to forbit using and 811 * updating the table while this command 812 * runs, by the command finding mechanism 813 * is heavily integrated with hash handling, 814 * so we just delete the hash before and after 815 * the command runs. Partly deleting like 816 * changepatch() does doesn't seem worth the 817 * bookinging effort, since most such runs add 818 * directories in front of the new PATH. 819 */ 820 clearcmdentry(); 821 do_clearcmdentry = 1; 822 } 823 824 for (;;) { 825 if (bltinonly) { 826 cmdentry.u.index = find_builtin(*argv, &cmdentry.special); 827 if (cmdentry.u.index < 0) { 828 cmdentry.u.index = BLTINCMD; 829 argv--; 830 argc++; 831 break; 832 } 833 } else 834 find_command(argv[0], &cmdentry, cmd_flags, path); 835 /* implement the bltin and command builtins here */ 836 if (cmdentry.cmdtype != CMDBUILTIN) 837 break; 838 if (cmdentry.u.index == BLTINCMD) { 839 if (argc == 1) 840 break; 841 argv++; 842 argc--; 843 bltinonly = 1; 844 } else if (cmdentry.u.index == COMMANDCMD) { 845 if (argc == 1) 846 break; 847 if (!strcmp(argv[1], "-p")) { 848 if (argc == 2) 849 break; 850 if (argv[2][0] == '-') { 851 if (strcmp(argv[2], "--")) 852 break; 853 if (argc == 3) 854 break; 855 argv += 3; 856 argc -= 3; 857 } else { 858 argv += 2; 859 argc -= 2; 860 } 861 path = _PATH_STDPATH; 862 clearcmdentry(); 863 do_clearcmdentry = 1; 864 } else if (!strcmp(argv[1], "--")) { 865 if (argc == 2) 866 break; 867 argv += 2; 868 argc -= 2; 869 } else if (argv[1][0] == '-') 870 break; 871 else { 872 argv++; 873 argc--; 874 } 875 cmd_flags |= DO_NOFUNC; 876 bltinonly = 0; 877 } else 878 break; 879 } 880 /* 881 * Special builtins lose their special properties when 882 * called via 'command'. 883 */ 884 if (cmd_flags & DO_NOFUNC) 885 cmdentry.special = 0; 886 } 887 888 /* Fork off a child process if necessary. */ 889 if (cmd->ncmd.backgnd 890 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN) 891 && ((flags & EV_EXIT) == 0 || have_traps())) 892 || ((flags & EV_BACKCMD) != 0 893 && (cmdentry.cmdtype != CMDBUILTIN || 894 !safe_builtin(cmdentry.u.index, argc, argv)))) { 895 jp = makejob(cmd, 1); 896 mode = cmd->ncmd.backgnd; 897 if (flags & EV_BACKCMD) { 898 mode = FORK_NOJOB; 899 if (pipe(pip) < 0) 900 error("Pipe call failed: %s", strerror(errno)); 901 } 902 if (forkshell(jp, cmd, mode) != 0) 903 goto parent; /* at end of routine */ 904 if (flags & EV_BACKCMD) { 905 FORCEINTON; 906 close(pip[0]); 907 if (pip[1] != 1) { 908 dup2(pip[1], 1); 909 close(pip[1]); 910 } 911 } 912 flags |= EV_EXIT; 913 } 914 915 /* This is the child process if a fork occurred. */ 916 /* Execute the command. */ 917 if (cmdentry.cmdtype == CMDFUNCTION) { 918 #ifdef DEBUG 919 trputs("Shell function: "); trargs(argv); 920 #endif 921 saveparam = shellparam; 922 shellparam.malloc = 0; 923 shellparam.reset = 1; 924 shellparam.nparam = argc - 1; 925 shellparam.p = argv + 1; 926 shellparam.optnext = NULL; 927 INTOFF; 928 savelocalvars = localvars; 929 localvars = NULL; 930 reffunc(cmdentry.u.func); 931 savehandler = handler; 932 if (setjmp(jmploc.loc)) { 933 freeparam(&shellparam); 934 shellparam = saveparam; 935 popredir(); 936 unreffunc(cmdentry.u.func); 937 poplocalvars(); 938 localvars = savelocalvars; 939 funcnest--; 940 handler = savehandler; 941 longjmp(handler->loc, 1); 942 } 943 handler = &jmploc; 944 funcnest++; 945 redirect(cmd->ncmd.redirect, REDIR_PUSH); 946 INTON; 947 for (sp = varlist.list ; sp ; sp = sp->next) 948 mklocal(sp->text); 949 exitstatus = oexitstatus; 950 evaltree(getfuncnode(cmdentry.u.func), 951 flags & (EV_TESTED | EV_EXIT)); 952 INTOFF; 953 unreffunc(cmdentry.u.func); 954 poplocalvars(); 955 localvars = savelocalvars; 956 freeparam(&shellparam); 957 shellparam = saveparam; 958 handler = savehandler; 959 funcnest--; 960 popredir(); 961 INTON; 962 if (evalskip == SKIPFUNC) { 963 evalskip = 0; 964 skipcount = 0; 965 } 966 if (jp) 967 exitshell(exitstatus); 968 } else if (cmdentry.cmdtype == CMDBUILTIN) { 969 #ifdef DEBUG 970 trputs("builtin command: "); trargs(argv); 971 #endif 972 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH; 973 if (flags == EV_BACKCMD) { 974 memout.nleft = 0; 975 memout.nextc = memout.buf; 976 memout.bufsize = 64; 977 mode |= REDIR_BACKQ; 978 cmdentry.special = 0; 979 } 980 savecmdname = commandname; 981 savetopfile = getcurrentfile(); 982 cmdenviron = varlist.list; 983 e = -1; 984 savehandler = handler; 985 if (setjmp(jmploc.loc)) { 986 e = exception; 987 if (e == EXINT) 988 exitstatus = SIGINT+128; 989 else if (e != EXEXIT) 990 exitstatus = 2; 991 goto cmddone; 992 } 993 handler = &jmploc; 994 redirect(cmd->ncmd.redirect, mode); 995 /* 996 * If there is no command word, redirection errors should 997 * not be fatal but assignment errors should. 998 */ 999 if (argc == 0 && !(flags & EV_BACKCMD)) 1000 cmdentry.special = 1; 1001 listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET); 1002 if (argc > 0) 1003 bltinsetlocale(); 1004 commandname = argv[0]; 1005 argptr = argv + 1; 1006 nextopt_optptr = NULL; /* initialize nextopt */ 1007 builtin_flags = flags; 1008 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv); 1009 flushall(); 1010 cmddone: 1011 if (argc > 0) 1012 bltinunsetlocale(); 1013 cmdenviron = NULL; 1014 out1 = &output; 1015 out2 = &errout; 1016 freestdout(); 1017 handler = savehandler; 1018 commandname = savecmdname; 1019 if (jp) 1020 exitshell(exitstatus); 1021 if (flags == EV_BACKCMD) { 1022 backcmd->buf = memout.buf; 1023 backcmd->nleft = memout.nextc - memout.buf; 1024 memout.buf = NULL; 1025 } 1026 if (cmdentry.u.index != EXECCMD) 1027 popredir(); 1028 if (e != -1) { 1029 if ((e != EXERROR && e != EXEXEC) 1030 || cmdentry.special) 1031 exraise(e); 1032 popfilesupto(savetopfile); 1033 if (flags != EV_BACKCMD) 1034 FORCEINTON; 1035 } 1036 } else { 1037 #ifdef DEBUG 1038 trputs("normal command: "); trargs(argv); 1039 #endif 1040 redirect(cmd->ncmd.redirect, 0); 1041 for (sp = varlist.list ; sp ; sp = sp->next) 1042 setvareq(sp->text, VEXPORT|VSTACK); 1043 envp = environment(); 1044 shellexec(argv, envp, path, cmdentry.u.index); 1045 /*NOTREACHED*/ 1046 } 1047 goto out; 1048 1049 parent: /* parent process gets here (if we forked) */ 1050 if (mode == FORK_FG) { /* argument to fork */ 1051 INTOFF; 1052 exitstatus = waitforjob(jp, &realstatus); 1053 INTON; 1054 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) { 1055 evalskip = SKIPBREAK; 1056 skipcount = loopnest; 1057 } 1058 } else if (mode == FORK_NOJOB) { 1059 backcmd->fd = pip[0]; 1060 close(pip[1]); 1061 backcmd->jp = jp; 1062 } 1063 1064 out: 1065 if (lastarg) 1066 setvar("_", lastarg, 0); 1067 if (do_clearcmdentry) 1068 clearcmdentry(); 1069 popstackmark(&smark); 1070 } 1071 1072 1073 1074 /* 1075 * Search for a command. This is called before we fork so that the 1076 * location of the command will be available in the parent as well as 1077 * the child. The check for "goodname" is an overly conservative 1078 * check that the name will not be subject to expansion. 1079 */ 1080 1081 static void 1082 prehash(union node *n) 1083 { 1084 struct cmdentry entry; 1085 1086 if (n && n->type == NCMD && n->ncmd.args) 1087 if (goodname(n->ncmd.args->narg.text)) 1088 find_command(n->ncmd.args->narg.text, &entry, 0, 1089 pathval()); 1090 } 1091 1092 1093 1094 /* 1095 * Builtin commands. Builtin commands whose functions are closely 1096 * tied to evaluation are implemented here. 1097 */ 1098 1099 /* 1100 * No command given, a bltin command with no arguments, or a bltin command 1101 * with an invalid name. 1102 */ 1103 1104 int 1105 bltincmd(int argc, char **argv) 1106 { 1107 if (argc > 1) { 1108 out2fmt_flush("%s: not found\n", argv[1]); 1109 return 127; 1110 } 1111 /* 1112 * Preserve exitstatus of a previous possible redirection 1113 * as POSIX mandates 1114 */ 1115 return exitstatus; 1116 } 1117 1118 1119 /* 1120 * Handle break and continue commands. Break, continue, and return are 1121 * all handled by setting the evalskip flag. The evaluation routines 1122 * above all check this flag, and if it is set they start skipping 1123 * commands rather than executing them. The variable skipcount is 1124 * the number of loops to break/continue, or the number of function 1125 * levels to return. (The latter is always 1.) It should probably 1126 * be an error to break out of more loops than exist, but it isn't 1127 * in the standard shell so we don't make it one here. 1128 */ 1129 1130 int 1131 breakcmd(int argc, char **argv) 1132 { 1133 int n = argc > 1 ? number(argv[1]) : 1; 1134 1135 if (n > loopnest) 1136 n = loopnest; 1137 if (n > 0) { 1138 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK; 1139 skipcount = n; 1140 } 1141 return 0; 1142 } 1143 1144 /* 1145 * The `command' command. 1146 */ 1147 int 1148 commandcmd(int argc, char **argv) 1149 { 1150 const char *path; 1151 int ch; 1152 int cmd = -1; 1153 1154 path = bltinlookup("PATH", 1); 1155 1156 optind = optreset = 1; 1157 opterr = 0; 1158 while ((ch = getopt(argc, argv, "pvV")) != -1) { 1159 switch (ch) { 1160 case 'p': 1161 path = _PATH_STDPATH; 1162 break; 1163 case 'v': 1164 cmd = TYPECMD_SMALLV; 1165 break; 1166 case 'V': 1167 cmd = TYPECMD_BIGV; 1168 break; 1169 case '?': 1170 default: 1171 error("unknown option: -%c", optopt); 1172 } 1173 } 1174 argc -= optind; 1175 argv += optind; 1176 1177 if (cmd != -1) { 1178 if (argc != 1) 1179 error("wrong number of arguments"); 1180 return typecmd_impl(2, argv - 1, cmd, path); 1181 } 1182 if (argc != 0) 1183 error("commandcmd bad call"); 1184 1185 /* 1186 * Do nothing successfully if no command was specified; 1187 * ksh also does this. 1188 */ 1189 return(0); 1190 } 1191 1192 1193 /* 1194 * The return command. 1195 */ 1196 1197 int 1198 returncmd(int argc, char **argv) 1199 { 1200 int ret = argc > 1 ? number(argv[1]) : oexitstatus; 1201 1202 if (funcnest) { 1203 evalskip = SKIPFUNC; 1204 skipcount = 1; 1205 } else { 1206 /* skip the rest of the file */ 1207 evalskip = SKIPFILE; 1208 skipcount = 1; 1209 } 1210 return ret; 1211 } 1212 1213 1214 int 1215 falsecmd(int argc __unused, char **argv __unused) 1216 { 1217 return 1; 1218 } 1219 1220 1221 int 1222 truecmd(int argc __unused, char **argv __unused) 1223 { 1224 return 0; 1225 } 1226 1227 1228 int 1229 execcmd(int argc, char **argv) 1230 { 1231 /* 1232 * Because we have historically not supported any options, 1233 * only treat "--" specially. 1234 */ 1235 if (argc > 1 && strcmp(argv[1], "--") == 0) 1236 argc--, argv++; 1237 if (argc > 1) { 1238 struct strlist *sp; 1239 1240 iflag = 0; /* exit on error */ 1241 mflag = 0; 1242 optschanged(); 1243 for (sp = cmdenviron; sp ; sp = sp->next) 1244 setvareq(sp->text, VEXPORT|VSTACK); 1245 shellexec(argv + 1, environment(), pathval(), 0); 1246 1247 } 1248 return 0; 1249 } 1250 1251 1252 int 1253 timescmd(int argc __unused, char **argv __unused) 1254 { 1255 struct rusage ru; 1256 long shumins, shsmins, chumins, chsmins; 1257 double shusecs, shssecs, chusecs, chssecs; 1258 1259 if (getrusage(RUSAGE_SELF, &ru) < 0) 1260 return 1; 1261 shumins = ru.ru_utime.tv_sec / 60; 1262 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1263 shsmins = ru.ru_stime.tv_sec / 60; 1264 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1265 if (getrusage(RUSAGE_CHILDREN, &ru) < 0) 1266 return 1; 1267 chumins = ru.ru_utime.tv_sec / 60; 1268 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1269 chsmins = ru.ru_stime.tv_sec / 60; 1270 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1271 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins, 1272 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs); 1273 return 0; 1274 } 1275