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