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 * @(#)eval.c 8.9 (Berkeley) 6/8/95 33 * $FreeBSD: head/bin/sh/eval.c 247206 2013-02-23 22:50:57Z jilles $ 34 */ 35 36 #include <sys/time.h> 37 #include <sys/resource.h> 38 #include <sys/wait.h> /* For WIFSIGNALED(status) */ 39 40 #include <errno.h> 41 #include <paths.h> 42 #include <signal.h> 43 #include <stdlib.h> 44 #include <unistd.h> 45 46 /* 47 * Evaluate a command. 48 */ 49 50 #include "shell.h" 51 #include "nodes.h" 52 #include "syntax.h" 53 #include "expand.h" 54 #include "parser.h" 55 #include "jobs.h" 56 #include "eval.h" 57 #include "builtins.h" 58 #include "options.h" 59 #include "exec.h" 60 #include "redir.h" 61 #include "input.h" 62 #include "output.h" 63 #include "trap.h" 64 #include "var.h" 65 #include "memalloc.h" 66 #include "error.h" 67 #include "show.h" 68 #include "mystring.h" 69 #ifndef NO_HISTORY 70 #include "myhistedit.h" 71 #endif 72 73 74 int evalskip; /* set if we are skipping commands */ 75 int skipcount; /* number of levels to skip */ 76 MKINIT int loopnest; /* current loop nesting level */ 77 int funcnest; /* depth of function calls */ 78 static int builtin_flags; /* evalcommand flags for builtins */ 79 80 81 const char *commandname; 82 struct strlist *cmdenviron; 83 int exitstatus; /* exit status of last command */ 84 int oexitstatus; /* saved exit status */ 85 86 87 static void evalloop(union node *, int); 88 static void evalfor(union node *, int); 89 static union node *evalcase(union node *); 90 static void evalsubshell(union node *, int); 91 static void evalredir(union node *, int); 92 static void exphere(union node *, struct arglist *); 93 static void expredir(union node *); 94 static void evalpipe(union node *); 95 static int is_valid_fast_cmdsubst(union node *n); 96 static void evalcommand(union node *, int, struct backcmd *); 97 static void prehash(union node *); 98 99 100 /* 101 * Called to reset things after an exception. 102 */ 103 104 #ifdef mkinit 105 INCLUDE "eval.h" 106 107 RESET { 108 evalskip = 0; 109 loopnest = 0; 110 funcnest = 0; 111 } 112 #endif 113 114 115 116 /* 117 * The eval command. 118 */ 119 120 int 121 evalcmd(int argc, char **argv) 122 { 123 char *p; 124 char *concat; 125 char **ap; 126 127 if (argc > 1) { 128 p = argv[1]; 129 if (argc > 2) { 130 STARTSTACKSTR(concat); 131 ap = argv + 2; 132 for (;;) { 133 STPUTS(p, concat); 134 if ((p = *ap++) == NULL) 135 break; 136 STPUTC(' ', concat); 137 } 138 STPUTC('\0', concat); 139 p = grabstackstr(concat); 140 } 141 evalstring(p, builtin_flags); 142 } else 143 exitstatus = 0; 144 return exitstatus; 145 } 146 147 148 /* 149 * Execute a command or commands contained in a string. 150 */ 151 152 void 153 evalstring(char *s, int flags) 154 { 155 union node *n; 156 struct stackmark smark; 157 int flags_exit; 158 int any; 159 160 flags_exit = flags & EV_EXIT; 161 flags &= ~EV_EXIT; 162 any = 0; 163 setstackmark(&smark); 164 setinputstring(s, 1); 165 while ((n = parsecmd(0)) != NEOF) { 166 if (n != NULL && !nflag) { 167 if (flags_exit && preadateof()) 168 evaltree(n, flags | EV_EXIT); 169 else 170 evaltree(n, flags); 171 any = 1; 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 exitstatus = !exitstatus; 280 break; 281 282 case NPIPE: 283 evalpipe(n); 284 do_etest = !(flags & EV_TESTED); 285 break; 286 case NCMD: 287 evalcommand(n, flags, NULL); 288 do_etest = !(flags & EV_TESTED); 289 break; 290 default: 291 out1fmt("Node type = %d\n", n->type); 292 flushout(&output); 293 break; 294 } 295 n = next; 296 popstackmark(&smark); 297 setstackmark(&smark); 298 } while (n != NULL); 299 out: 300 popstackmark(&smark); 301 if (pendingsig) 302 dotrap(); 303 if (eflag && exitstatus != 0 && do_etest) 304 exitshell(exitstatus); 305 if (flags & EV_EXIT) 306 exraise(EXEXIT); 307 } 308 309 310 static void 311 evalloop(union node *n, int flags) 312 { 313 int status; 314 315 loopnest++; 316 status = 0; 317 for (;;) { 318 evaltree(n->nbinary.ch1, EV_TESTED); 319 if (evalskip) { 320 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { 321 evalskip = 0; 322 continue; 323 } 324 if (evalskip == SKIPBREAK && --skipcount <= 0) 325 evalskip = 0; 326 if (evalskip == SKIPFUNC || evalskip == SKIPFILE) 327 status = exitstatus; 328 break; 329 } 330 if (n->type == NWHILE) { 331 if (exitstatus != 0) 332 break; 333 } else { 334 if (exitstatus == 0) 335 break; 336 } 337 evaltree(n->nbinary.ch2, flags); 338 status = exitstatus; 339 if (evalskip) 340 goto skipping; 341 } 342 loopnest--; 343 exitstatus = status; 344 } 345 346 347 348 static void 349 evalfor(union node *n, int flags) 350 { 351 struct arglist arglist; 352 union node *argp; 353 struct strlist *sp; 354 int status; 355 356 arglist.lastp = &arglist.list; 357 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { 358 oexitstatus = exitstatus; 359 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 360 } 361 *arglist.lastp = NULL; 362 363 loopnest++; 364 status = 0; 365 for (sp = arglist.list ; sp ; sp = sp->next) { 366 setvar(n->nfor.var, sp->text, 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 arglist.lastp = &arglist.list; 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.list->text)) { 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, 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 exitstatus = 2; 472 return; 473 } 474 } 475 longjmp(handler->loc, 1); 476 } else { 477 INTOFF; 478 handler = &jmploc; 479 redirect(n->nredir.redirect, REDIR_PUSH); 480 in_redirect = 0; 481 INTON; 482 evaltree(n->nredir.n, flags); 483 } 484 INTOFF; 485 handler = savehandler; 486 popredir(); 487 INTON; 488 } 489 490 491 static void 492 exphere(union node *redir, struct arglist *fn) 493 { 494 struct jmploc jmploc; 495 struct jmploc *savehandler; 496 struct localvar *savelocalvars; 497 int need_longjmp = 0; 498 499 redir->nhere.expdoc = nullstr; 500 savelocalvars = localvars; 501 localvars = NULL; 502 forcelocal++; 503 savehandler = handler; 504 if (setjmp(jmploc.loc)) 505 need_longjmp = exception != EXERROR && exception != EXEXEC; 506 else { 507 handler = &jmploc; 508 expandarg(redir->nhere.doc, fn, 0); 509 redir->nhere.expdoc = fn->list->text; 510 INTOFF; 511 } 512 handler = savehandler; 513 forcelocal--; 514 poplocalvars(); 515 localvars = savelocalvars; 516 if (need_longjmp) 517 longjmp(handler->loc, 1); 518 INTON; 519 } 520 521 522 /* 523 * Compute the names of the files in a redirection list. 524 */ 525 526 static void 527 expredir(union node *n) 528 { 529 union node *redir; 530 531 for (redir = n ; redir ; redir = redir->nfile.next) { 532 struct arglist fn; 533 fn.lastp = &fn.list; 534 switch (redir->type) { 535 case NFROM: 536 case NTO: 537 case NFROMTO: 538 case NAPPEND: 539 case NCLOBBER: 540 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR); 541 redir->nfile.expfname = fn.list->text; 542 break; 543 case NFROMFD: 544 case NTOFD: 545 if (redir->ndup.vname) { 546 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR); 547 fixredir(redir, fn.list->text, 1); 548 } 549 break; 550 case NXHERE: 551 exphere(redir, &fn); 552 break; 553 } 554 } 555 } 556 557 558 559 /* 560 * Evaluate a pipeline. All the processes in the pipeline are children 561 * of the process creating the pipeline. (This differs from some versions 562 * of the shell, which make the last process in a pipeline the parent 563 * of all the rest.) 564 */ 565 566 static void 567 evalpipe(union node *n) 568 { 569 struct job *jp; 570 struct nodelist *lp; 571 int pipelen; 572 int prevfd; 573 int pip[2]; 574 575 TRACE(("evalpipe(%p) called\n", (void *)n)); 576 pipelen = 0; 577 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) 578 pipelen++; 579 INTOFF; 580 jp = makejob(n, pipelen); 581 prevfd = -1; 582 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) { 583 prehash(lp->n); 584 pip[1] = -1; 585 if (lp->next) { 586 if (pipe(pip) < 0) { 587 if (prevfd >= 0) 588 close(prevfd); 589 error("Pipe call failed: %s", strerror(errno)); 590 } 591 } 592 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) { 593 INTON; 594 if (prevfd > 0) { 595 dup2(prevfd, 0); 596 close(prevfd); 597 } 598 if (pip[1] >= 0) { 599 if (!(prevfd >= 0 && pip[0] == 0)) 600 close(pip[0]); 601 if (pip[1] != 1) { 602 dup2(pip[1], 1); 603 close(pip[1]); 604 } 605 } 606 evaltree(lp->n, EV_EXIT); 607 } 608 if (prevfd >= 0) 609 close(prevfd); 610 prevfd = pip[0]; 611 if (pip[1] != -1) 612 close(pip[1]); 613 } 614 INTON; 615 if (n->npipe.backgnd == 0) { 616 INTOFF; 617 exitstatus = waitforjob(jp, NULL); 618 TRACE(("evalpipe: job done exit status %d\n", exitstatus)); 619 INTON; 620 } else 621 exitstatus = 0; 622 } 623 624 625 626 static int 627 is_valid_fast_cmdsubst(union node *n) 628 { 629 630 return (n->type == NCMD); 631 } 632 633 /* 634 * Execute a command inside back quotes. If it's a builtin command, we 635 * want to save its output in a block obtained from malloc. Otherwise 636 * we fork off a subprocess and get the output of the command via a pipe. 637 * Should be called with interrupts off. 638 */ 639 640 void 641 evalbackcmd(union node *n, struct backcmd *result) 642 { 643 int pip[2]; 644 struct job *jp; 645 struct stackmark smark; 646 struct jmploc jmploc; 647 struct jmploc *savehandler; 648 struct localvar *savelocalvars; 649 650 setstackmark(&smark); 651 result->fd = -1; 652 result->buf = NULL; 653 result->nleft = 0; 654 result->jp = NULL; 655 if (n == NULL) { 656 exitstatus = 0; 657 goto out; 658 } 659 exitstatus = oexitstatus; 660 if (is_valid_fast_cmdsubst(n)) { 661 savelocalvars = localvars; 662 localvars = NULL; 663 forcelocal++; 664 savehandler = handler; 665 if (setjmp(jmploc.loc)) { 666 if (exception == EXERROR || exception == EXEXEC) 667 exitstatus = 2; 668 else if (exception != 0) { 669 handler = savehandler; 670 forcelocal--; 671 poplocalvars(); 672 localvars = savelocalvars; 673 longjmp(handler->loc, 1); 674 } 675 } else { 676 handler = &jmploc; 677 evalcommand(n, EV_BACKCMD, result); 678 } 679 handler = savehandler; 680 forcelocal--; 681 poplocalvars(); 682 localvars = savelocalvars; 683 } else { 684 if (pipe(pip) < 0) 685 error("Pipe call failed: %s", strerror(errno)); 686 jp = makejob(n, 1); 687 if (forkshell(jp, n, FORK_NOJOB) == 0) { 688 FORCEINTON; 689 close(pip[0]); 690 if (pip[1] != 1) { 691 dup2(pip[1], 1); 692 close(pip[1]); 693 } 694 evaltree(n, EV_EXIT); 695 } 696 close(pip[1]); 697 result->fd = pip[0]; 698 result->jp = jp; 699 } 700 out: 701 popstackmark(&smark); 702 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n", 703 result->fd, result->buf, result->nleft, result->jp)); 704 } 705 706 static int 707 mustexpandto(const char *argtext, const char *mask) 708 { 709 for (;;) { 710 if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) { 711 argtext++; 712 continue; 713 } 714 if (*argtext == CTLESC) 715 argtext++; 716 else if (BASESYNTAX[(int)*argtext] == CCTL) 717 return (0); 718 if (*argtext != *mask) 719 return (0); 720 if (*argtext == '\0') 721 return (1); 722 argtext++; 723 mask++; 724 } 725 } 726 727 static int 728 isdeclarationcmd(struct narg *arg) 729 { 730 int have_command = 0; 731 732 if (arg == NULL) 733 return (0); 734 while (mustexpandto(arg->text, "command")) { 735 have_command = 1; 736 arg = &arg->next->narg; 737 if (arg == NULL) 738 return (0); 739 /* 740 * To also allow "command -p" and "command --" as part of 741 * a declaration command, add code here. 742 * We do not do this, as ksh does not do it either and it 743 * is not required by POSIX. 744 */ 745 } 746 return (mustexpandto(arg->text, "export") || 747 mustexpandto(arg->text, "readonly") || 748 (mustexpandto(arg->text, "local") && 749 (have_command || !isfunc("local")))); 750 } 751 752 /* 753 * Check if a builtin can safely be executed in the same process, 754 * even though it should be in a subshell (command substitution). 755 * Note that jobid, jobs, times and trap can show information not 756 * available in a child process; this is deliberate. 757 * The arguments should already have been expanded. 758 */ 759 static int 760 safe_builtin(int idx, int argc, char **argv) 761 { 762 if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD || 763 idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD || 764 idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD || 765 idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD || 766 idx == TYPECMD) 767 return (1); 768 if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || 769 idx == UMASKCMD) 770 return (argc <= 1 || (argc == 2 && argv[1][0] == '-')); 771 if (idx == SETCMD) 772 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' || 773 argv[1][0] == '+') && argv[1][1] == 'o' && 774 argv[1][2] == '\0')); 775 return (0); 776 } 777 778 /* 779 * Execute a simple command. 780 * Note: This may or may not return if (flags & EV_EXIT). 781 */ 782 783 static void 784 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd) 785 { 786 union node *argp; 787 struct arglist arglist; 788 struct arglist varlist; 789 volatile int flags = flgs; 790 char **volatile argv; 791 volatile 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 *volatile jp; 799 struct jmploc jmploc; 800 struct jmploc *savehandler; 801 const char *savecmdname; 802 struct shparam saveparam; 803 struct localvar *savelocalvars; 804 struct parsefile *savetopfile; 805 volatile int e; 806 char *volatile lastarg; 807 int realstatus; 808 volatile 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 == SKIPFUNC) { 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 if (funcnest) { 1309 evalskip = SKIPFUNC; 1310 skipcount = 1; 1311 } else { 1312 /* skip the rest of the file */ 1313 evalskip = SKIPFILE; 1314 skipcount = 1; 1315 } 1316 return ret; 1317 } 1318 1319 1320 int 1321 falsecmd(int argc __unused, char **argv __unused) 1322 { 1323 return 1; 1324 } 1325 1326 1327 int 1328 truecmd(int argc __unused, char **argv __unused) 1329 { 1330 return 0; 1331 } 1332 1333 1334 int 1335 execcmd(int argc, char **argv) 1336 { 1337 /* 1338 * Because we have historically not supported any options, 1339 * only treat "--" specially. 1340 */ 1341 if (argc > 1 && strcmp(argv[1], "--") == 0) 1342 argc--, argv++; 1343 if (argc > 1) { 1344 struct strlist *sp; 1345 1346 iflag = 0; /* exit on error */ 1347 mflag = 0; 1348 optschanged(); 1349 for (sp = cmdenviron; sp ; sp = sp->next) 1350 setvareq(sp->text, VEXPORT|VSTACK); 1351 shellexec(argv + 1, environment(), pathval(), 0); 1352 1353 } 1354 return 0; 1355 } 1356 1357 1358 int 1359 timescmd(int argc __unused, char **argv __unused) 1360 { 1361 struct rusage ru; 1362 long shumins, shsmins, chumins, chsmins; 1363 double shusecs, shssecs, chusecs, chssecs; 1364 1365 if (getrusage(RUSAGE_SELF, &ru) < 0) 1366 return 1; 1367 shumins = ru.ru_utime.tv_sec / 60; 1368 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1369 shsmins = ru.ru_stime.tv_sec / 60; 1370 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1371 if (getrusage(RUSAGE_CHILDREN, &ru) < 0) 1372 return 1; 1373 chumins = ru.ru_utime.tv_sec / 60; 1374 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1375 chsmins = ru.ru_stime.tv_sec / 60; 1376 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1377 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins, 1378 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs); 1379 return 0; 1380 } 1381