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