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