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