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