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