eval.c revision 216826
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 216826 2010-12-30 22:33:55Z 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 115SHELLPROC { 116 exitstatus = 0; 117} 118#endif 119 120 121 122/* 123 * The eval command. 124 */ 125 126int 127evalcmd(int argc, char **argv) 128{ 129 char *p; 130 char *concat; 131 char **ap; 132 133 if (argc > 1) { 134 p = argv[1]; 135 if (argc > 2) { 136 STARTSTACKSTR(concat); 137 ap = argv + 2; 138 for (;;) { 139 STPUTS(p, concat); 140 if ((p = *ap++) == NULL) 141 break; 142 STPUTC(' ', concat); 143 } 144 STPUTC('\0', concat); 145 p = grabstackstr(concat); 146 } 147 evalstring(p, builtin_flags & EV_TESTED); 148 } else 149 exitstatus = 0; 150 return exitstatus; 151} 152 153 154/* 155 * Execute a command or commands contained in a string. 156 */ 157 158void 159evalstring(char *s, int flags) 160{ 161 union node *n; 162 struct stackmark smark; 163 int flags_exit; 164 int any; 165 166 flags_exit = flags & EV_EXIT; 167 flags &= ~EV_EXIT; 168 any = 0; 169 setstackmark(&smark); 170 setinputstring(s, 1); 171 while ((n = parsecmd(0)) != NEOF) { 172 if (n != NULL) { 173 if (flags_exit && preadateof()) 174 evaltree(n, flags | EV_EXIT); 175 else 176 evaltree(n, flags); 177 any = 1; 178 } 179 popstackmark(&smark); 180 } 181 popfile(); 182 popstackmark(&smark); 183 if (!any) 184 exitstatus = 0; 185 if (flags_exit) 186 exitshell(exitstatus); 187} 188 189 190/* 191 * Evaluate a parse tree. The value is left in the global variable 192 * exitstatus. 193 */ 194 195void 196evaltree(union node *n, int flags) 197{ 198 int do_etest; 199 union node *next; 200 201 do_etest = 0; 202 if (n == NULL) { 203 TRACE(("evaltree(NULL) called\n")); 204 exitstatus = 0; 205 goto out; 206 } 207 do { 208 next = NULL; 209#ifndef NO_HISTORY 210 displayhist = 1; /* show history substitutions done with fc */ 211#endif 212 TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type)); 213 switch (n->type) { 214 case NSEMI: 215 evaltree(n->nbinary.ch1, flags & ~EV_EXIT); 216 if (evalskip) 217 goto out; 218 next = n->nbinary.ch2; 219 break; 220 case NAND: 221 evaltree(n->nbinary.ch1, EV_TESTED); 222 if (evalskip || exitstatus != 0) { 223 goto out; 224 } 225 next = n->nbinary.ch2; 226 break; 227 case NOR: 228 evaltree(n->nbinary.ch1, EV_TESTED); 229 if (evalskip || exitstatus == 0) 230 goto out; 231 next = n->nbinary.ch2; 232 break; 233 case NREDIR: 234 evalredir(n, flags); 235 break; 236 case NSUBSHELL: 237 evalsubshell(n, flags); 238 do_etest = !(flags & EV_TESTED); 239 break; 240 case NBACKGND: 241 evalsubshell(n, flags); 242 break; 243 case NIF: { 244 evaltree(n->nif.test, EV_TESTED); 245 if (evalskip) 246 goto out; 247 if (exitstatus == 0) 248 next = n->nif.ifpart; 249 else if (n->nif.elsepart) 250 next = n->nif.elsepart; 251 else 252 exitstatus = 0; 253 break; 254 } 255 case NWHILE: 256 case NUNTIL: 257 evalloop(n, flags & ~EV_EXIT); 258 break; 259 case NFOR: 260 evalfor(n, flags & ~EV_EXIT); 261 break; 262 case NCASE: 263 evalcase(n, flags); 264 break; 265 case NDEFUN: 266 defun(n->narg.text, n->narg.next); 267 exitstatus = 0; 268 break; 269 case NNOT: 270 evaltree(n->nnot.com, EV_TESTED); 271 exitstatus = !exitstatus; 272 break; 273 274 case NPIPE: 275 evalpipe(n); 276 do_etest = !(flags & EV_TESTED); 277 break; 278 case NCMD: 279 evalcommand(n, flags, (struct backcmd *)NULL); 280 do_etest = !(flags & EV_TESTED); 281 break; 282 default: 283 out1fmt("Node type = %d\n", n->type); 284 flushout(&output); 285 break; 286 } 287 n = next; 288 } while (n != NULL); 289out: 290 if (pendingsigs) 291 dotrap(); 292 if ((flags & EV_EXIT) || (eflag && exitstatus != 0 && do_etest)) 293 exitshell(exitstatus); 294} 295 296 297static void 298evalloop(union node *n, int flags) 299{ 300 int status; 301 302 loopnest++; 303 status = 0; 304 for (;;) { 305 evaltree(n->nbinary.ch1, EV_TESTED); 306 if (evalskip) { 307skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { 308 evalskip = 0; 309 continue; 310 } 311 if (evalskip == SKIPBREAK && --skipcount <= 0) 312 evalskip = 0; 313 if (evalskip == SKIPFUNC || evalskip == SKIPFILE) 314 status = exitstatus; 315 break; 316 } 317 if (n->type == NWHILE) { 318 if (exitstatus != 0) 319 break; 320 } else { 321 if (exitstatus == 0) 322 break; 323 } 324 evaltree(n->nbinary.ch2, flags); 325 status = exitstatus; 326 if (evalskip) 327 goto skipping; 328 } 329 loopnest--; 330 exitstatus = status; 331} 332 333 334 335static void 336evalfor(union node *n, int flags) 337{ 338 struct arglist arglist; 339 union node *argp; 340 struct strlist *sp; 341 struct stackmark smark; 342 343 setstackmark(&smark); 344 arglist.lastp = &arglist.list; 345 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { 346 oexitstatus = exitstatus; 347 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 348 if (evalskip) 349 goto out; 350 } 351 *arglist.lastp = NULL; 352 353 exitstatus = 0; 354 loopnest++; 355 for (sp = arglist.list ; sp ; sp = sp->next) { 356 setvar(n->nfor.var, sp->text, 0); 357 evaltree(n->nfor.body, flags); 358 if (evalskip) { 359 if (evalskip == SKIPCONT && --skipcount <= 0) { 360 evalskip = 0; 361 continue; 362 } 363 if (evalskip == SKIPBREAK && --skipcount <= 0) 364 evalskip = 0; 365 break; 366 } 367 } 368 loopnest--; 369out: 370 popstackmark(&smark); 371} 372 373 374 375static void 376evalcase(union node *n, int flags) 377{ 378 union node *cp; 379 union node *patp; 380 struct arglist arglist; 381 struct stackmark smark; 382 383 setstackmark(&smark); 384 arglist.lastp = &arglist.list; 385 oexitstatus = exitstatus; 386 exitstatus = 0; 387 expandarg(n->ncase.expr, &arglist, EXP_TILDE); 388 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) { 389 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) { 390 if (casematch(patp, arglist.list->text)) { 391 if (evalskip == 0) { 392 evaltree(cp->nclist.body, flags); 393 } 394 goto out; 395 } 396 } 397 } 398out: 399 popstackmark(&smark); 400} 401 402 403 404/* 405 * Kick off a subshell to evaluate a tree. 406 */ 407 408static void 409evalsubshell(union node *n, int flags) 410{ 411 struct job *jp; 412 int backgnd = (n->type == NBACKGND); 413 414 expredir(n->nredir.redirect); 415 if ((!backgnd && flags & EV_EXIT && !have_traps()) || 416 forkshell(jp = makejob(n, 1), n, backgnd) == 0) { 417 if (backgnd) 418 flags &=~ EV_TESTED; 419 redirect(n->nredir.redirect, 0); 420 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */ 421 } else if (! backgnd) { 422 INTOFF; 423 exitstatus = waitforjob(jp, (int *)NULL); 424 INTON; 425 } 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 expredir(n->nredir.redirect); 441 savehandler = handler; 442 if (setjmp(jmploc.loc)) { 443 int e; 444 445 handler = savehandler; 446 e = exception; 447 if (e == EXERROR || e == EXEXEC) { 448 popredir(); 449 if (in_redirect) { 450 exitstatus = 2; 451 return; 452 } 453 } 454 longjmp(handler->loc, 1); 455 } else { 456 INTOFF; 457 handler = &jmploc; 458 redirect(n->nredir.redirect, REDIR_PUSH); 459 in_redirect = 0; 460 INTON; 461 evaltree(n->nredir.n, flags); 462 } 463 INTOFF; 464 handler = savehandler; 465 popredir(); 466 INTON; 467} 468 469 470/* 471 * Compute the names of the files in a redirection list. 472 */ 473 474static void 475expredir(union node *n) 476{ 477 union node *redir; 478 479 for (redir = n ; redir ; redir = redir->nfile.next) { 480 struct arglist fn; 481 fn.lastp = &fn.list; 482 oexitstatus = exitstatus; 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 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 } 565} 566 567 568 569static int 570is_valid_fast_cmdsubst(union node *n) 571{ 572 union node *argp; 573 574 if (n->type != NCMD) 575 return 0; 576 for (argp = n->ncmd.args ; argp ; argp = argp->narg.next) 577 if (expandhassideeffects(argp->narg.text)) 578 return 0; 579 return 1; 580} 581 582/* 583 * Execute a command inside back quotes. If it's a builtin command, we 584 * want to save its output in a block obtained from malloc. Otherwise 585 * we fork off a subprocess and get the output of the command via a pipe. 586 * Should be called with interrupts off. 587 */ 588 589void 590evalbackcmd(union node *n, struct backcmd *result) 591{ 592 int pip[2]; 593 struct job *jp; 594 struct stackmark smark; /* unnecessary */ 595 struct jmploc jmploc; 596 struct jmploc *savehandler; 597 598 setstackmark(&smark); 599 result->fd = -1; 600 result->buf = NULL; 601 result->nleft = 0; 602 result->jp = NULL; 603 if (n == NULL) { 604 exitstatus = 0; 605 goto out; 606 } 607 if (is_valid_fast_cmdsubst(n)) { 608 exitstatus = oexitstatus; 609 savehandler = handler; 610 if (setjmp(jmploc.loc)) { 611 if (exception == EXERROR || exception == EXEXEC) 612 exitstatus = 2; 613 else if (exception != 0) { 614 handler = savehandler; 615 longjmp(handler->loc, 1); 616 } 617 } else { 618 handler = &jmploc; 619 evalcommand(n, EV_BACKCMD, result); 620 } 621 handler = savehandler; 622 } else { 623 exitstatus = 0; 624 if (pipe(pip) < 0) 625 error("Pipe call failed: %s", strerror(errno)); 626 jp = makejob(n, 1); 627 if (forkshell(jp, n, FORK_NOJOB) == 0) { 628 FORCEINTON; 629 close(pip[0]); 630 if (pip[1] != 1) { 631 dup2(pip[1], 1); 632 close(pip[1]); 633 } 634 evaltree(n, EV_EXIT); 635 } 636 close(pip[1]); 637 result->fd = pip[0]; 638 result->jp = jp; 639 } 640out: 641 popstackmark(&smark); 642 TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n", 643 result->fd, result->buf, result->nleft, result->jp)); 644} 645 646/* 647 * Check if a builtin can safely be executed in the same process, 648 * even though it should be in a subshell (command substitution). 649 * Note that jobid, jobs, times and trap can show information not 650 * available in a child process; this is deliberate. 651 * The arguments should already have been expanded. 652 */ 653static int 654safe_builtin(int idx, int argc, char **argv) 655{ 656 if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD || 657 idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD || 658 idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD || 659 idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD || 660 idx == TYPECMD) 661 return (1); 662 if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || 663 idx == UMASKCMD) 664 return (argc <= 1 || (argc == 2 && argv[1][0] == '-')); 665 if (idx == SETCMD) 666 return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' || 667 argv[1][0] == '+') && argv[1][1] == 'o' && 668 argv[1][2] == '\0')); 669 return (0); 670} 671 672/* 673 * Execute a simple command. 674 */ 675 676static void 677evalcommand(union node *cmd, int flags, struct backcmd *backcmd) 678{ 679 struct stackmark smark; 680 union node *argp; 681 struct arglist arglist; 682 struct arglist varlist; 683 char **argv; 684 int argc; 685 char **envp; 686 int varflag; 687 struct strlist *sp; 688 int mode; 689 int pip[2]; 690 struct cmdentry cmdentry; 691 struct job *jp; 692 struct jmploc jmploc; 693 struct jmploc *savehandler; 694 char *savecmdname; 695 struct shparam saveparam; 696 struct localvar *savelocalvars; 697 struct parsefile *savetopfile; 698 volatile int e; 699 char *lastarg; 700 int realstatus; 701 int do_clearcmdentry; 702 const char *path = pathval(); 703 704 /* First expand the arguments. */ 705 TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags)); 706 setstackmark(&smark); 707 arglist.lastp = &arglist.list; 708 varlist.lastp = &varlist.list; 709 varflag = 1; 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 argv = stalloc(sizeof (char *) * (argc + 1)); 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; 749 out2str(ps4val()); 750 for (sp = varlist.list ; sp ; sp = sp->next) { 751 if (sep != 0) 752 out2c(' '); 753 p = strchr(sp->text, '='); 754 if (p != NULL) { 755 p++; 756 outbin(sp->text, p - sp->text, out2); 757 out2qstr(p); 758 } else 759 out2qstr(sp->text); 760 sep = ' '; 761 } 762 for (sp = arglist.list ; sp ; sp = sp->next) { 763 if (sep != 0) 764 out2c(' '); 765 /* Disambiguate command looking like assignment. */ 766 if (sp == arglist.list && 767 strchr(sp->text, '=') != NULL && 768 strchr(sp->text, '\'') == NULL) { 769 out2c('\''); 770 out2str(sp->text); 771 out2c('\''); 772 } else 773 out2qstr(sp->text); 774 sep = ' '; 775 } 776 out2c('\n'); 777 flushout(&errout); 778 } 779 780 /* Now locate the command. */ 781 if (argc == 0) { 782 /* Variable assignment(s) without command */ 783 cmdentry.cmdtype = CMDBUILTIN; 784 cmdentry.u.index = BLTINCMD; 785 cmdentry.special = 0; 786 } else { 787 static const char PATH[] = "PATH="; 788 int cmd_flags = 0, bltinonly = 0; 789 790 /* 791 * Modify the command lookup path, if a PATH= assignment 792 * is present 793 */ 794 for (sp = varlist.list ; sp ; sp = sp->next) 795 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) { 796 path = sp->text + sizeof(PATH) - 1; 797 /* 798 * On `PATH=... command`, we need to make 799 * sure that the command isn't using the 800 * non-updated hash table of the outer PATH 801 * setting and we need to make sure that 802 * the hash table isn't filled with items 803 * from the temporary setting. 804 * 805 * It would be better to forbit using and 806 * updating the table while this command 807 * runs, by the command finding mechanism 808 * is heavily integrated with hash handling, 809 * so we just delete the hash before and after 810 * the command runs. Partly deleting like 811 * changepatch() does doesn't seem worth the 812 * bookinging effort, since most such runs add 813 * directories in front of the new PATH. 814 */ 815 clearcmdentry(0); 816 do_clearcmdentry = 1; 817 } 818 819 for (;;) { 820 if (bltinonly) { 821 cmdentry.u.index = find_builtin(*argv, &cmdentry.special); 822 if (cmdentry.u.index < 0) { 823 cmdentry.u.index = BLTINCMD; 824 argv--; 825 argc++; 826 break; 827 } 828 } else 829 find_command(argv[0], &cmdentry, cmd_flags, path); 830 /* implement the bltin and command builtins here */ 831 if (cmdentry.cmdtype != CMDBUILTIN) 832 break; 833 if (cmdentry.u.index == BLTINCMD) { 834 if (argc == 1) 835 break; 836 argv++; 837 argc--; 838 bltinonly = 1; 839 } else if (cmdentry.u.index == COMMANDCMD) { 840 if (argc == 1) 841 break; 842 if (!strcmp(argv[1], "-p")) { 843 if (argc == 2) 844 break; 845 if (argv[2][0] == '-') { 846 if (strcmp(argv[2], "--")) 847 break; 848 if (argc == 3) 849 break; 850 argv += 3; 851 argc -= 3; 852 } else { 853 argv += 2; 854 argc -= 2; 855 } 856 path = _PATH_STDPATH; 857 clearcmdentry(0); 858 do_clearcmdentry = 1; 859 } else if (!strcmp(argv[1], "--")) { 860 if (argc == 2) 861 break; 862 argv += 2; 863 argc -= 2; 864 } else if (argv[1][0] == '-') 865 break; 866 else { 867 argv++; 868 argc--; 869 } 870 cmd_flags |= DO_NOFUNC; 871 bltinonly = 0; 872 } else 873 break; 874 } 875 /* 876 * Special builtins lose their special properties when 877 * called via 'command'. 878 */ 879 if (cmd_flags & DO_NOFUNC) 880 cmdentry.special = 0; 881 } 882 883 /* Fork off a child process if necessary. */ 884 if (cmd->ncmd.backgnd 885 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN) 886 && ((flags & EV_EXIT) == 0 || have_traps())) 887 || ((flags & EV_BACKCMD) != 0 888 && (cmdentry.cmdtype != CMDBUILTIN || 889 !safe_builtin(cmdentry.u.index, argc, argv)))) { 890 jp = makejob(cmd, 1); 891 mode = cmd->ncmd.backgnd; 892 if (flags & EV_BACKCMD) { 893 mode = FORK_NOJOB; 894 if (pipe(pip) < 0) 895 error("Pipe call failed: %s", strerror(errno)); 896 } 897 if (forkshell(jp, cmd, mode) != 0) 898 goto parent; /* at end of routine */ 899 if (flags & EV_BACKCMD) { 900 FORCEINTON; 901 close(pip[0]); 902 if (pip[1] != 1) { 903 dup2(pip[1], 1); 904 close(pip[1]); 905 } 906 } 907 flags |= EV_EXIT; 908 } 909 910 /* This is the child process if a fork occurred. */ 911 /* Execute the command. */ 912 if (cmdentry.cmdtype == CMDFUNCTION) { 913#ifdef DEBUG 914 trputs("Shell function: "); trargs(argv); 915#endif 916 saveparam = shellparam; 917 shellparam.malloc = 0; 918 shellparam.reset = 1; 919 shellparam.nparam = argc - 1; 920 shellparam.p = argv + 1; 921 shellparam.optnext = NULL; 922 INTOFF; 923 savelocalvars = localvars; 924 localvars = NULL; 925 reffunc(cmdentry.u.func); 926 savehandler = handler; 927 if (setjmp(jmploc.loc)) { 928 if (exception == EXSHELLPROC) 929 freeparam(&saveparam); 930 else { 931 freeparam(&shellparam); 932 shellparam = saveparam; 933 if (exception == EXERROR || exception == EXEXEC) 934 popredir(); 935 } 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 if (flags & EV_TESTED) 951 evaltree(getfuncnode(cmdentry.u.func), EV_TESTED); 952 else 953 evaltree(getfuncnode(cmdentry.u.func), 0); 954 INTOFF; 955 unreffunc(cmdentry.u.func); 956 poplocalvars(); 957 localvars = savelocalvars; 958 freeparam(&shellparam); 959 shellparam = saveparam; 960 handler = savehandler; 961 funcnest--; 962 popredir(); 963 INTON; 964 if (evalskip == SKIPFUNC) { 965 evalskip = 0; 966 skipcount = 0; 967 } 968 if (flags & EV_EXIT) 969 exitshell(exitstatus); 970 } else if (cmdentry.cmdtype == CMDBUILTIN) { 971#ifdef DEBUG 972 trputs("builtin command: "); trargs(argv); 973#endif 974 mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH; 975 if (flags == EV_BACKCMD) { 976 memout.nleft = 0; 977 memout.nextc = memout.buf; 978 memout.bufsize = 64; 979 mode |= REDIR_BACKQ; 980 cmdentry.special = 0; 981 } 982 savecmdname = commandname; 983 savetopfile = getcurrentfile(); 984 cmdenviron = varlist.list; 985 e = -1; 986 savehandler = handler; 987 if (setjmp(jmploc.loc)) { 988 e = exception; 989 exitstatus = (e == EXINT)? SIGINT+128 : 2; 990 goto cmddone; 991 } 992 handler = &jmploc; 993 redirect(cmd->ncmd.redirect, mode); 994 /* 995 * If there is no command word, redirection errors should 996 * not be fatal but assignment errors should. 997 */ 998 if (argc == 0 && !(flags & EV_BACKCMD)) 999 cmdentry.special = 1; 1000 if (cmdentry.special) 1001 listsetvar(cmdenviron); 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 if (e != EXSHELLPROC) { 1018 commandname = savecmdname; 1019 if (flags & EV_EXIT) { 1020 exitshell(exitstatus); 1021 } 1022 } 1023 handler = savehandler; 1024 if (flags == EV_BACKCMD) { 1025 backcmd->buf = memout.buf; 1026 backcmd->nleft = memout.nextc - memout.buf; 1027 memout.buf = NULL; 1028 } 1029 if (cmdentry.u.index != EXECCMD && 1030 (e == -1 || e == EXERROR || e == EXEXEC)) 1031 popredir(); 1032 if (e != -1) { 1033 if ((e != EXERROR && e != EXEXEC) 1034 || cmdentry.special) 1035 exraise(e); 1036 popfilesupto(savetopfile); 1037 if (flags != EV_BACKCMD) 1038 FORCEINTON; 1039 } 1040 } else { 1041#ifdef DEBUG 1042 trputs("normal command: "); trargs(argv); 1043#endif 1044 redirect(cmd->ncmd.redirect, 0); 1045 for (sp = varlist.list ; sp ; sp = sp->next) 1046 setvareq(sp->text, VEXPORT|VSTACK); 1047 envp = environment(); 1048 shellexec(argv, envp, path, cmdentry.u.index); 1049 /*NOTREACHED*/ 1050 } 1051 goto out; 1052 1053parent: /* parent process gets here (if we forked) */ 1054 if (mode == FORK_FG) { /* argument to fork */ 1055 INTOFF; 1056 exitstatus = waitforjob(jp, &realstatus); 1057 INTON; 1058 if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) { 1059 evalskip = SKIPBREAK; 1060 skipcount = loopnest; 1061 } 1062 } else if (mode == FORK_NOJOB) { 1063 backcmd->fd = pip[0]; 1064 close(pip[1]); 1065 backcmd->jp = jp; 1066 } 1067 1068out: 1069 if (lastarg) 1070 setvar("_", lastarg, 0); 1071 if (do_clearcmdentry) 1072 clearcmdentry(0); 1073 popstackmark(&smark); 1074} 1075 1076 1077 1078/* 1079 * Search for a command. This is called before we fork so that the 1080 * location of the command will be available in the parent as well as 1081 * the child. The check for "goodname" is an overly conservative 1082 * check that the name will not be subject to expansion. 1083 */ 1084 1085static void 1086prehash(union node *n) 1087{ 1088 struct cmdentry entry; 1089 1090 if (n && n->type == NCMD && n->ncmd.args) 1091 if (goodname(n->ncmd.args->narg.text)) 1092 find_command(n->ncmd.args->narg.text, &entry, 0, 1093 pathval()); 1094} 1095 1096 1097 1098/* 1099 * Builtin commands. Builtin commands whose functions are closely 1100 * tied to evaluation are implemented here. 1101 */ 1102 1103/* 1104 * No command given, a bltin command with no arguments, or a bltin command 1105 * with an invalid name. 1106 */ 1107 1108int 1109bltincmd(int argc, char **argv) 1110{ 1111 if (argc > 1) { 1112 out2fmt_flush("%s: not found\n", argv[1]); 1113 return 127; 1114 } 1115 /* 1116 * Preserve exitstatus of a previous possible redirection 1117 * as POSIX mandates 1118 */ 1119 return exitstatus; 1120} 1121 1122 1123/* 1124 * Handle break and continue commands. Break, continue, and return are 1125 * all handled by setting the evalskip flag. The evaluation routines 1126 * above all check this flag, and if it is set they start skipping 1127 * commands rather than executing them. The variable skipcount is 1128 * the number of loops to break/continue, or the number of function 1129 * levels to return. (The latter is always 1.) It should probably 1130 * be an error to break out of more loops than exist, but it isn't 1131 * in the standard shell so we don't make it one here. 1132 */ 1133 1134int 1135breakcmd(int argc, char **argv) 1136{ 1137 int n = argc > 1 ? number(argv[1]) : 1; 1138 1139 if (n > loopnest) 1140 n = loopnest; 1141 if (n > 0) { 1142 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK; 1143 skipcount = n; 1144 } 1145 return 0; 1146} 1147 1148/* 1149 * The `command' command. 1150 */ 1151int 1152commandcmd(int argc, char **argv) 1153{ 1154 const char *path; 1155 int ch; 1156 int cmd = -1; 1157 1158 path = bltinlookup("PATH", 1); 1159 1160 optind = optreset = 1; 1161 opterr = 0; 1162 while ((ch = getopt(argc, argv, "pvV")) != -1) { 1163 switch (ch) { 1164 case 'p': 1165 path = _PATH_STDPATH; 1166 break; 1167 case 'v': 1168 cmd = TYPECMD_SMALLV; 1169 break; 1170 case 'V': 1171 cmd = TYPECMD_BIGV; 1172 break; 1173 case '?': 1174 default: 1175 error("unknown option: -%c", optopt); 1176 } 1177 } 1178 argc -= optind; 1179 argv += optind; 1180 1181 if (cmd != -1) { 1182 if (argc != 1) 1183 error("wrong number of arguments"); 1184 return typecmd_impl(2, argv - 1, cmd, path); 1185 } 1186 if (argc != 0) 1187 error("commandcmd bad call"); 1188 1189 /* 1190 * Do nothing successfully if no command was specified; 1191 * ksh also does this. 1192 */ 1193 return 0; 1194} 1195 1196 1197/* 1198 * The return command. 1199 */ 1200 1201int 1202returncmd(int argc, char **argv) 1203{ 1204 int ret = argc > 1 ? number(argv[1]) : oexitstatus; 1205 1206 if (funcnest) { 1207 evalskip = SKIPFUNC; 1208 skipcount = 1; 1209 } else { 1210 /* skip the rest of the file */ 1211 evalskip = SKIPFILE; 1212 skipcount = 1; 1213 } 1214 return ret; 1215} 1216 1217 1218int 1219falsecmd(int argc __unused, char **argv __unused) 1220{ 1221 return 1; 1222} 1223 1224 1225int 1226truecmd(int argc __unused, char **argv __unused) 1227{ 1228 return 0; 1229} 1230 1231 1232int 1233execcmd(int argc, char **argv) 1234{ 1235 /* 1236 * Because we have historically not supported any options, 1237 * only treat "--" specially. 1238 */ 1239 if (argc > 1 && strcmp(argv[1], "--") == 0) 1240 argc--, argv++; 1241 if (argc > 1) { 1242 struct strlist *sp; 1243 1244 iflag = 0; /* exit on error */ 1245 mflag = 0; 1246 optschanged(); 1247 for (sp = cmdenviron; sp ; sp = sp->next) 1248 setvareq(sp->text, VEXPORT|VSTACK); 1249 shellexec(argv + 1, environment(), pathval(), 0); 1250 1251 } 1252 return 0; 1253} 1254 1255 1256int 1257timescmd(int argc __unused, char **argv __unused) 1258{ 1259 struct rusage ru; 1260 long shumins, shsmins, chumins, chsmins; 1261 double shusecs, shssecs, chusecs, chssecs; 1262 1263 if (getrusage(RUSAGE_SELF, &ru) < 0) 1264 return 1; 1265 shumins = ru.ru_utime.tv_sec / 60; 1266 shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1267 shsmins = ru.ru_stime.tv_sec / 60; 1268 shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1269 if (getrusage(RUSAGE_CHILDREN, &ru) < 0) 1270 return 1; 1271 chumins = ru.ru_utime.tv_sec / 60; 1272 chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; 1273 chsmins = ru.ru_stime.tv_sec / 60; 1274 chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; 1275 out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins, 1276 shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs); 1277 return 0; 1278} 1279