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