eval.c revision 220978
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 220978 2011-04-23 22:28:56Z 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 } 424} 425 426 427/* 428 * Evaluate a redirected compound command. 429 */ 430 431static void 432evalredir(union node *n, int flags) 433{ 434 struct jmploc jmploc; 435 struct jmploc *savehandler; 436 volatile int in_redirect = 1; 437 438 expredir(n->nredir.redirect); 439 savehandler = handler; 440 if (setjmp(jmploc.loc)) { 441 int e; 442 443 handler = savehandler; 444 e = exception; 445 popredir(); 446 if (e == EXERROR || e == EXEXEC) { 447 if (in_redirect) { 448 exitstatus = 2; 449 return; 450 } 451 } 452 longjmp(handler->loc, 1); 453 } else { 454 INTOFF; 455 handler = &jmploc; 456 redirect(n->nredir.redirect, REDIR_PUSH); 457 in_redirect = 0; 458 INTON; 459 evaltree(n->nredir.n, flags); 460 } 461 INTOFF; 462 handler = savehandler; 463 popredir(); 464 INTON; 465} 466 467 468/* 469 * Compute the names of the files in a redirection list. 470 */ 471 472static void 473expredir(union node *n) 474{ 475 union node *redir; 476 477 for (redir = n ; redir ; redir = redir->nfile.next) { 478 struct arglist fn; 479 fn.lastp = &fn.list; 480 oexitstatus = exitstatus; 481 switch (redir->type) { 482 case NFROM: 483 case NTO: 484 case NFROMTO: 485 case NAPPEND: 486 case NCLOBBER: 487 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR); 488 redir->nfile.expfname = fn.list->text; 489 break; 490 case NFROMFD: 491 case NTOFD: 492 if (redir->ndup.vname) { 493 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR); 494 fixredir(redir, fn.list->text, 1); 495 } 496 break; 497 } 498 } 499} 500 501 502 503/* 504 * Evaluate a pipeline. All the processes in the pipeline are children 505 * of the process creating the pipeline. (This differs from some versions 506 * of the shell, which make the last process in a pipeline the parent 507 * of all the rest.) 508 */ 509 510static void 511evalpipe(union node *n) 512{ 513 struct job *jp; 514 struct nodelist *lp; 515 int pipelen; 516 int prevfd; 517 int pip[2]; 518 519 TRACE(("evalpipe(%p) called\n", (void *)n)); 520 pipelen = 0; 521 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) 522 pipelen++; 523 INTOFF; 524 jp = makejob(n, pipelen); 525 prevfd = -1; 526 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) { 527 prehash(lp->n); 528 pip[1] = -1; 529 if (lp->next) { 530 if (pipe(pip) < 0) { 531 close(prevfd); 532 error("Pipe call failed: %s", strerror(errno)); 533 } 534 } 535 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) { 536 INTON; 537 if (prevfd > 0) { 538 dup2(prevfd, 0); 539 close(prevfd); 540 } 541 if (pip[1] >= 0) { 542 if (!(prevfd >= 0 && pip[0] == 0)) 543 close(pip[0]); 544 if (pip[1] != 1) { 545 dup2(pip[1], 1); 546 close(pip[1]); 547 } 548 } 549 evaltree(lp->n, EV_EXIT); 550 } 551 if (prevfd >= 0) 552 close(prevfd); 553 prevfd = pip[0]; 554 close(pip[1]); 555 } 556 INTON; 557 if (n->npipe.backgnd == 0) { 558 INTOFF; 559 exitstatus = waitforjob(jp, (int *)NULL); 560 TRACE(("evalpipe: job done exit status %d\n", exitstatus)); 561 INTON; 562 } 563} 564 565 566 567static int 568is_valid_fast_cmdsubst(union node *n) 569{ 570 union node *argp; 571 572 if (n->type != NCMD) 573 return 0; 574 for (argp = n->ncmd.args ; argp ; argp = argp->narg.next) 575 if (expandhassideeffects(argp->narg.text)) 576 return 0; 577 return 1; 578} 579 580/* 581 * Execute a command inside back quotes. If it's a builtin command, we 582 * want to save its output in a block obtained from malloc. Otherwise 583 * we fork off a subprocess and get the output of the command via a pipe. 584 * Should be called with interrupts off. 585 */ 586 587void 588evalbackcmd(union node *n, struct backcmd *result) 589{ 590 int pip[2]; 591 struct job *jp; 592 struct stackmark smark; /* unnecessary */ 593 struct jmploc jmploc; 594 struct jmploc *savehandler; 595 596 setstackmark(&smark); 597 result->fd = -1; 598 result->buf = NULL; 599 result->nleft = 0; 600 result->jp = NULL; 601 if (n == NULL) { 602 exitstatus = 0; 603 goto out; 604 } 605 if (is_valid_fast_cmdsubst(n)) { 606 exitstatus = oexitstatus; 607 savehandler = handler; 608 if (setjmp(jmploc.loc)) { 609 if (exception == EXERROR || exception == EXEXEC) 610 exitstatus = 2; 611 else if (exception != 0) { 612 handler = savehandler; 613 longjmp(handler->loc, 1); 614 } 615 } else { 616 handler = &jmploc; 617 evalcommand(n, EV_BACKCMD, result); 618 } 619 handler = savehandler; 620 } else { 621 exitstatus = 0; 622 if (pipe(pip) < 0) 623 error("Pipe call failed: %s", strerror(errno)); 624 jp = makejob(n, 1); 625 if (forkshell(jp, n, FORK_NOJOB) == 0) { 626 FORCEINTON; 627 close(pip[0]); 628 if (pip[1] != 1) { 629 dup2(pip[1], 1); 630 close(pip[1]); 631 } 632 evaltree(n, EV_EXIT); 633 } 634 close(pip[1]); 635 result->fd = pip[0]; 636 result->jp = jp; 637 } 638out: 639 popstackmark(&smark); 640 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n", 641 result->fd, result->buf, result->nleft, result->jp)); 642} 643 644/* 645 * Check if a builtin can safely be executed in the same process, 646 * even though it should be in a subshell (command substitution). 647 * Note that jobid, jobs, times and trap can show information not 648 * available in a child process; this is deliberate. 649 * The arguments should already have been expanded. 650 */ 651static int 652safe_builtin(int idx, int argc, char **argv) 653{ 654 if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD || 655 idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD || 656 idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD || 657 idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD || 658 idx == TYPECMD) 659 return (1); 660 if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || 661 idx == UMASKCMD) 662 return (argc <= 1 || (argc == 2 && argv[1][0] == '-')); 663 if (idx == SETCMD) 664 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' || 665 argv[1][0] == '+') && argv[1][1] == 'o' && 666 argv[1][2] == '\0')); 667 return (0); 668} 669 670/* 671 * Execute a simple command. 672 * Note: This may or may not return if (flags & EV_EXIT). 673 */ 674 675static void 676evalcommand(union node *cmd, int flags, struct backcmd *backcmd) 677{ 678 struct stackmark smark; 679 union node *argp; 680 struct arglist arglist; 681 struct arglist varlist; 682 char **argv; 683 int argc; 684 char **envp; 685 int varflag; 686 struct strlist *sp; 687 int mode; 688 int pip[2]; 689 struct cmdentry cmdentry; 690 struct job *jp; 691 struct jmploc jmploc; 692 struct jmploc *savehandler; 693 char *savecmdname; 694 struct shparam saveparam; 695 struct localvar *savelocalvars; 696 struct parsefile *savetopfile; 697 volatile int e; 698 char *lastarg; 699 int realstatus; 700 int do_clearcmdentry; 701 const char *path = pathval(); 702 703 /* First expand the arguments. */ 704 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags)); 705 setstackmark(&smark); 706 arglist.lastp = &arglist.list; 707 varlist.lastp = &varlist.list; 708 varflag = 1; 709 jp = NULL; 710 do_clearcmdentry = 0; 711 oexitstatus = exitstatus; 712 exitstatus = 0; 713 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { 714 char *p = argp->narg.text; 715 if (varflag && is_name(*p)) { 716 do { 717 p++; 718 } while (is_in_name(*p)); 719 if (*p == '=') { 720 expandarg(argp, &varlist, EXP_VARTILDE); 721 continue; 722 } 723 } 724 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 725 varflag = 0; 726 } 727 *arglist.lastp = NULL; 728 *varlist.lastp = NULL; 729 expredir(cmd->ncmd.redirect); 730 argc = 0; 731 for (sp = arglist.list ; sp ; sp = sp->next) 732 argc++; 733 /* Add one slot at the beginning for tryexec(). */ 734 argv = stalloc(sizeof (char *) * (argc + 2)); 735 argv++; 736 737 for (sp = arglist.list ; sp ; sp = sp->next) { 738 TRACE(("evalcommand arg: %s\n", sp->text)); 739 *argv++ = sp->text; 740 } 741 *argv = NULL; 742 lastarg = NULL; 743 if (iflag && funcnest == 0 && argc > 0) 744 lastarg = argv[-1]; 745 argv -= argc; 746 747 /* Print the command if xflag is set. */ 748 if (xflag) { 749 char sep = 0; 750 const char *p; 751 out2str(ps4val()); 752 for (sp = varlist.list ; sp ; sp = sp->next) { 753 if (sep != 0) 754 out2c(' '); 755 p = strchr(sp->text, '='); 756 if (p != NULL) { 757 p++; 758 outbin(sp->text, p - sp->text, out2); 759 out2qstr(p); 760 } else 761 out2qstr(sp->text); 762 sep = ' '; 763 } 764 for (sp = arglist.list ; sp ; sp = sp->next) { 765 if (sep != 0) 766 out2c(' '); 767 /* Disambiguate command looking like assignment. */ 768 if (sp == arglist.list && 769 strchr(sp->text, '=') != NULL && 770 strchr(sp->text, '\'') == NULL) { 771 out2c('\''); 772 out2str(sp->text); 773 out2c('\''); 774 } else 775 out2qstr(sp->text); 776 sep = ' '; 777 } 778 out2c('\n'); 779 flushout(&errout); 780 } 781 782 /* Now locate the command. */ 783 if (argc == 0) { 784 /* Variable assignment(s) without command */ 785 cmdentry.cmdtype = CMDBUILTIN; 786 cmdentry.u.index = BLTINCMD; 787 cmdentry.special = 0; 788 } else { 789 static const char PATH[] = "PATH="; 790 int cmd_flags = 0, bltinonly = 0; 791 792 /* 793 * Modify the command lookup path, if a PATH= assignment 794 * is present 795 */ 796 for (sp = varlist.list ; sp ; sp = sp->next) 797 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) { 798 path = sp->text + sizeof(PATH) - 1; 799 /* 800 * On `PATH=... command`, we need to make 801 * sure that the command isn't using the 802 * non-updated hash table of the outer PATH 803 * setting and we need to make sure that 804 * the hash table isn't filled with items 805 * from the temporary setting. 806 * 807 * It would be better to forbit using and 808 * updating the table while this command 809 * runs, by the command finding mechanism 810 * is heavily integrated with hash handling, 811 * so we just delete the hash before and after 812 * the command runs. Partly deleting like 813 * changepatch() does doesn't seem worth the 814 * bookinging effort, since most such runs add 815 * directories in front of the new PATH. 816 */ 817 clearcmdentry(); 818 do_clearcmdentry = 1; 819 } 820 821 for (;;) { 822 if (bltinonly) { 823 cmdentry.u.index = find_builtin(*argv, &cmdentry.special); 824 if (cmdentry.u.index < 0) { 825 cmdentry.u.index = BLTINCMD; 826 argv--; 827 argc++; 828 break; 829 } 830 } else 831 find_command(argv[0], &cmdentry, cmd_flags, path); 832 /* implement the bltin and command builtins here */ 833 if (cmdentry.cmdtype != CMDBUILTIN) 834 break; 835 if (cmdentry.u.index == BLTINCMD) { 836 if (argc == 1) 837 break; 838 argv++; 839 argc--; 840 bltinonly = 1; 841 } else if (cmdentry.u.index == COMMANDCMD) { 842 if (argc == 1) 843 break; 844 if (!strcmp(argv[1], "-p")) { 845 if (argc == 2) 846 break; 847 if (argv[2][0] == '-') { 848 if (strcmp(argv[2], "--")) 849 break; 850 if (argc == 3) 851 break; 852 argv += 3; 853 argc -= 3; 854 } else { 855 argv += 2; 856 argc -= 2; 857 } 858 path = _PATH_STDPATH; 859 clearcmdentry(); 860 do_clearcmdentry = 1; 861 } else if (!strcmp(argv[1], "--")) { 862 if (argc == 2) 863 break; 864 argv += 2; 865 argc -= 2; 866 } else if (argv[1][0] == '-') 867 break; 868 else { 869 argv++; 870 argc--; 871 } 872 cmd_flags |= DO_NOFUNC; 873 bltinonly = 0; 874 } else 875 break; 876 } 877 /* 878 * Special builtins lose their special properties when 879 * called via 'command'. 880 */ 881 if (cmd_flags & DO_NOFUNC) 882 cmdentry.special = 0; 883 } 884 885 /* Fork off a child process if necessary. */ 886 if (cmd->ncmd.backgnd 887 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN) 888 && ((flags & EV_EXIT) == 0 || have_traps())) 889 || ((flags & EV_BACKCMD) != 0 890 && (cmdentry.cmdtype != CMDBUILTIN || 891 !safe_builtin(cmdentry.u.index, argc, argv)))) { 892 jp = makejob(cmd, 1); 893 mode = cmd->ncmd.backgnd; 894 if (flags & EV_BACKCMD) { 895 mode = FORK_NOJOB; 896 if (pipe(pip) < 0) 897 error("Pipe call failed: %s", strerror(errno)); 898 } 899 if (forkshell(jp, cmd, mode) != 0) 900 goto parent; /* at end of routine */ 901 if (flags & EV_BACKCMD) { 902 FORCEINTON; 903 close(pip[0]); 904 if (pip[1] != 1) { 905 dup2(pip[1], 1); 906 close(pip[1]); 907 } 908 } 909 flags |= EV_EXIT; 910 } 911 912 /* This is the child process if a fork occurred. */ 913 /* Execute the command. */ 914 if (cmdentry.cmdtype == CMDFUNCTION) { 915#ifdef DEBUG 916 trputs("Shell function: "); trargs(argv); 917#endif 918 saveparam = shellparam; 919 shellparam.malloc = 0; 920 shellparam.reset = 1; 921 shellparam.nparam = argc - 1; 922 shellparam.p = argv + 1; 923 shellparam.optnext = NULL; 924 INTOFF; 925 savelocalvars = localvars; 926 localvars = NULL; 927 reffunc(cmdentry.u.func); 928 savehandler = handler; 929 if (setjmp(jmploc.loc)) { 930 freeparam(&shellparam); 931 shellparam = saveparam; 932 popredir(); 933 unreffunc(cmdentry.u.func); 934 poplocalvars(); 935 localvars = savelocalvars; 936 funcnest--; 937 handler = savehandler; 938 longjmp(handler->loc, 1); 939 } 940 handler = &jmploc; 941 funcnest++; 942 redirect(cmd->ncmd.redirect, REDIR_PUSH); 943 INTON; 944 for (sp = varlist.list ; sp ; sp = sp->next) 945 mklocal(sp->text); 946 exitstatus = oexitstatus; 947 evaltree(getfuncnode(cmdentry.u.func), 948 flags & (EV_TESTED | EV_EXIT)); 949 INTOFF; 950 unreffunc(cmdentry.u.func); 951 poplocalvars(); 952 localvars = savelocalvars; 953 freeparam(&shellparam); 954 shellparam = saveparam; 955 handler = savehandler; 956 funcnest--; 957 popredir(); 958 INTON; 959 if (evalskip == SKIPFUNC) { 960 evalskip = 0; 961 skipcount = 0; 962 } 963 if (jp) 964 exitshell(exitstatus); 965 } else if (cmdentry.cmdtype == CMDBUILTIN) { 966#ifdef DEBUG 967 trputs("builtin command: "); trargs(argv); 968#endif 969 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH; 970 if (flags == EV_BACKCMD) { 971 memout.nleft = 0; 972 memout.nextc = memout.buf; 973 memout.bufsize = 64; 974 mode |= REDIR_BACKQ; 975 cmdentry.special = 0; 976 } 977 savecmdname = commandname; 978 savetopfile = getcurrentfile(); 979 cmdenviron = varlist.list; 980 e = -1; 981 savehandler = handler; 982 if (setjmp(jmploc.loc)) { 983 e = exception; 984 if (e == EXINT) 985 exitstatus = SIGINT+128; 986 else if (e != EXEXIT) 987 exitstatus = 2; 988 goto cmddone; 989 } 990 handler = &jmploc; 991 redirect(cmd->ncmd.redirect, mode); 992 /* 993 * If there is no command word, redirection errors should 994 * not be fatal but assignment errors should. 995 */ 996 if (argc == 0 && !(flags & EV_BACKCMD)) 997 cmdentry.special = 1; 998 listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET); 999 if (argc > 0) 1000 bltinsetlocale(); 1001 commandname = argv[0]; 1002 argptr = argv + 1; 1003 nextopt_optptr = NULL; /* initialize nextopt */ 1004 builtin_flags = flags; 1005 exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv); 1006 flushall(); 1007cmddone: 1008 if (argc > 0) 1009 bltinunsetlocale(); 1010 cmdenviron = NULL; 1011 out1 = &output; 1012 out2 = &errout; 1013 freestdout(); 1014 handler = savehandler; 1015 commandname = savecmdname; 1016 if (jp) 1017 exitshell(exitstatus); 1018 if (flags == EV_BACKCMD) { 1019 backcmd->buf = memout.buf; 1020 backcmd->nleft = memout.nextc - memout.buf; 1021 memout.buf = NULL; 1022 } 1023 if (cmdentry.u.index != EXECCMD) 1024 popredir(); 1025 if (e != -1) { 1026 if ((e != EXERROR && e != EXEXEC) 1027 || cmdentry.special) 1028 exraise(e); 1029 popfilesupto(savetopfile); 1030 if (flags != EV_BACKCMD) 1031 FORCEINTON; 1032 } 1033 } else { 1034#ifdef DEBUG 1035 trputs("normal command: "); trargs(argv); 1036#endif 1037 redirect(cmd->ncmd.redirect, 0); 1038 for (sp = varlist.list ; sp ; sp = sp->next) 1039 setvareq(sp->text, VEXPORT|VSTACK); 1040 envp = environment(); 1041 shellexec(argv, envp, path, cmdentry.u.index); 1042 /*NOTREACHED*/ 1043 } 1044 goto out; 1045 1046parent: /* parent process gets here (if we forked) */ 1047 if (mode == FORK_FG) { /* argument to fork */ 1048 INTOFF; 1049 exitstatus = waitforjob(jp, &realstatus); 1050 INTON; 1051 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) { 1052 evalskip = SKIPBREAK; 1053 skipcount = loopnest; 1054 } 1055 } else if (mode == FORK_NOJOB) { 1056 backcmd->fd = pip[0]; 1057 close(pip[1]); 1058 backcmd->jp = jp; 1059 } 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