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