1 /* $NetBSD: eval.c,v 1.95 2008/12/21 03:15:32 christos Exp $ */ 2 3 /*- 4 * Copyright (c) 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Kenneth Almquist. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 #include <sys/cdefs.h> 36 #ifndef lint 37 #if 0 38 static char sccsid[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95"; 39 #else 40 __RCSID("$NetBSD: eval.c,v 1.95 2008/12/21 03:15:32 christos Exp $"); 41 #endif 42 #endif /* not lint */ 43 44 #include <stdbool.h> 45 #include <stdlib.h> 46 #include <signal.h> 47 #include <stdio.h> 48 #include <unistd.h> 49 #include <sys/fcntl.h> 50 #include <sys/times.h> 51 #include <sys/param.h> 52 #include <sys/types.h> 53 #include <sys/wait.h> 54 #include <sys/sysctl.h> 55 56 /* 57 * Evaluate a command. 58 */ 59 60 #include "shell.h" 61 #include "nodes.h" 62 #include "syntax.h" 63 #include "expand.h" 64 #include "parser.h" 65 #include "jobs.h" 66 #include "eval.h" 67 #include "builtins.h" 68 #include "options.h" 69 #include "exec.h" 70 #include "redir.h" 71 #include "input.h" 72 #include "output.h" 73 #include "trap.h" 74 #include "var.h" 75 #include "memalloc.h" 76 #include "error.h" 77 #include "show.h" 78 #include "mystring.h" 79 #include "main.h" 80 #ifndef SMALL 81 #include "myhistedit.h" 82 #endif 83 84 85 /* flags in argument to evaltree */ 86 #define EV_EXIT 01 /* exit after evaluating tree */ 87 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */ 88 #define EV_BACKCMD 04 /* command executing within back quotes */ 89 90 int evalskip; /* set if we are skipping commands */ 91 STATIC int skipcount; /* number of levels to skip */ 92 MKINIT int loopnest; /* current loop nesting level */ 93 int funcnest; /* depth of function calls */ 94 95 96 const char *commandname; 97 struct strlist *cmdenviron; 98 int exitstatus; /* exit status of last command */ 99 int back_exitstatus; /* exit status of backquoted command */ 100 101 102 STATIC void evalloop(union node *, int); 103 STATIC void evalfor(union node *, int); 104 STATIC void evalcase(union node *, int); 105 STATIC void evalsubshell(union node *, int); 106 STATIC void expredir(union node *); 107 STATIC void evalpipe(union node *); 108 STATIC void evalcommand(union node *, int, struct backcmd *); 109 STATIC void prehash(union node *); 110 111 112 /* 113 * Called to reset things after an exception. 114 */ 115 116 #ifdef mkinit 117 INCLUDE "eval.h" 118 119 RESET { 120 evalskip = 0; 121 loopnest = 0; 122 funcnest = 0; 123 } 124 125 SHELLPROC { 126 exitstatus = 0; 127 } 128 #endif 129 130 static int 131 sh_pipe(int fds[2]) 132 { 133 int nfd; 134 135 if (pipe(fds)) 136 return -1; 137 138 if (fds[0] < 3) { 139 nfd = fcntl(fds[0], F_DUPFD, 3); 140 if (nfd != -1) { 141 close(fds[0]); 142 fds[0] = nfd; 143 } 144 } 145 146 if (fds[1] < 3) { 147 nfd = fcntl(fds[1], F_DUPFD, 3); 148 if (nfd != -1) { 149 close(fds[1]); 150 fds[1] = nfd; 151 } 152 } 153 return 0; 154 } 155 156 157 /* 158 * The eval commmand. 159 */ 160 161 int 162 evalcmd(int argc, char **argv) 163 { 164 char *p; 165 char *concat; 166 char **ap; 167 168 if (argc > 1) { 169 p = argv[1]; 170 if (argc > 2) { 171 STARTSTACKSTR(concat); 172 ap = argv + 2; 173 for (;;) { 174 while (*p) 175 STPUTC(*p++, concat); 176 if ((p = *ap++) == NULL) 177 break; 178 STPUTC(' ', concat); 179 } 180 STPUTC('\0', concat); 181 p = grabstackstr(concat); 182 } 183 evalstring(p, EV_TESTED); 184 } 185 return exitstatus; 186 } 187 188 189 /* 190 * Execute a command or commands contained in a string. 191 */ 192 193 void 194 evalstring(char *s, int flag) 195 { 196 union node *n; 197 struct stackmark smark; 198 199 setstackmark(&smark); 200 setinputstring(s, 1); 201 202 while ((n = parsecmd(0)) != NEOF) { 203 evaltree(n, flag); 204 popstackmark(&smark); 205 } 206 popfile(); 207 popstackmark(&smark); 208 } 209 210 211 212 /* 213 * Evaluate a parse tree. The value is left in the global variable 214 * exitstatus. 215 */ 216 217 void 218 evaltree(union node *n, int flags) 219 { 220 bool do_etest; 221 222 do_etest = false; 223 if (n == NULL) { 224 TRACE(("evaltree(NULL) called\n")); 225 exitstatus = 0; 226 goto out; 227 } 228 #ifndef SMALL 229 displayhist = 1; /* show history substitutions done with fc */ 230 #endif 231 TRACE(("pid %d, evaltree(%p: %d, %d) called\n", 232 getpid(), n, n->type, flags)); 233 switch (n->type) { 234 case NSEMI: 235 evaltree(n->nbinary.ch1, flags & EV_TESTED); 236 if (evalskip) 237 goto out; 238 evaltree(n->nbinary.ch2, flags); 239 break; 240 case NAND: 241 evaltree(n->nbinary.ch1, EV_TESTED); 242 if (evalskip || exitstatus != 0) 243 goto out; 244 evaltree(n->nbinary.ch2, flags); 245 break; 246 case NOR: 247 evaltree(n->nbinary.ch1, EV_TESTED); 248 if (evalskip || exitstatus == 0) 249 goto out; 250 evaltree(n->nbinary.ch2, flags); 251 break; 252 case NREDIR: 253 expredir(n->nredir.redirect); 254 redirect(n->nredir.redirect, REDIR_PUSH); 255 evaltree(n->nredir.n, flags); 256 popredir(); 257 break; 258 case NSUBSHELL: 259 evalsubshell(n, flags); 260 do_etest = !(flags & EV_TESTED); 261 break; 262 case NBACKGND: 263 evalsubshell(n, flags); 264 break; 265 case NIF: { 266 evaltree(n->nif.test, EV_TESTED); 267 if (evalskip) 268 goto out; 269 if (exitstatus == 0) 270 evaltree(n->nif.ifpart, flags); 271 else if (n->nif.elsepart) 272 evaltree(n->nif.elsepart, flags); 273 else 274 exitstatus = 0; 275 break; 276 } 277 case NWHILE: 278 case NUNTIL: 279 evalloop(n, flags); 280 break; 281 case NFOR: 282 evalfor(n, flags); 283 break; 284 case NCASE: 285 evalcase(n, flags); 286 break; 287 case NDEFUN: 288 defun(n->narg.text, n->narg.next); 289 exitstatus = 0; 290 break; 291 case NNOT: 292 evaltree(n->nnot.com, EV_TESTED); 293 exitstatus = !exitstatus; 294 break; 295 case NPIPE: 296 evalpipe(n); 297 do_etest = !(flags & EV_TESTED); 298 break; 299 case NCMD: 300 evalcommand(n, flags, (struct backcmd *)NULL); 301 do_etest = !(flags & EV_TESTED); 302 break; 303 default: 304 out1fmt("Node type = %d\n", n->type); 305 flushout(&output); 306 break; 307 } 308 out: 309 if (pendingsigs) 310 dotrap(); 311 if ((flags & EV_EXIT) != 0 || (eflag && exitstatus != 0 && do_etest)) 312 exitshell(exitstatus); 313 } 314 315 316 STATIC void 317 evalloop(union node *n, int flags) 318 { 319 int status; 320 321 loopnest++; 322 status = 0; 323 for (;;) { 324 evaltree(n->nbinary.ch1, EV_TESTED); 325 if (evalskip) { 326 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { 327 evalskip = 0; 328 continue; 329 } 330 if (evalskip == SKIPBREAK && --skipcount <= 0) 331 evalskip = 0; 332 break; 333 } 334 if (n->type == NWHILE) { 335 if (exitstatus != 0) 336 break; 337 } else { 338 if (exitstatus == 0) 339 break; 340 } 341 evaltree(n->nbinary.ch2, flags & EV_TESTED); 342 status = exitstatus; 343 if (evalskip) 344 goto skipping; 345 } 346 loopnest--; 347 exitstatus = status; 348 } 349 350 351 352 STATIC void 353 evalfor(union node *n, int flags) 354 { 355 struct arglist arglist; 356 union node *argp; 357 struct strlist *sp; 358 struct stackmark smark; 359 int status = 0; 360 361 setstackmark(&smark); 362 arglist.lastp = &arglist.list; 363 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { 364 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 365 if (evalskip) 366 goto out; 367 } 368 *arglist.lastp = NULL; 369 370 loopnest++; 371 for (sp = arglist.list ; sp ; sp = sp->next) { 372 setvar(n->nfor.var, sp->text, 0); 373 evaltree(n->nfor.body, flags & EV_TESTED); 374 status = exitstatus; 375 if (evalskip) { 376 if (evalskip == SKIPCONT && --skipcount <= 0) { 377 evalskip = 0; 378 continue; 379 } 380 if (evalskip == SKIPBREAK && --skipcount <= 0) 381 evalskip = 0; 382 break; 383 } 384 } 385 loopnest--; 386 exitstatus = status; 387 out: 388 popstackmark(&smark); 389 } 390 391 392 393 STATIC void 394 evalcase(union node *n, int flags) 395 { 396 union node *cp; 397 union node *patp; 398 struct arglist arglist; 399 struct stackmark smark; 400 int status = 0; 401 402 setstackmark(&smark); 403 arglist.lastp = &arglist.list; 404 expandarg(n->ncase.expr, &arglist, EXP_TILDE); 405 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) { 406 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) { 407 if (casematch(patp, arglist.list->text)) { 408 if (evalskip == 0) { 409 evaltree(cp->nclist.body, flags); 410 status = exitstatus; 411 } 412 goto out; 413 } 414 } 415 } 416 out: 417 exitstatus = status; 418 popstackmark(&smark); 419 } 420 421 422 423 /* 424 * Kick off a subshell to evaluate a tree. 425 */ 426 427 STATIC void 428 evalsubshell(union node *n, int flags) 429 { 430 struct job *jp; 431 int backgnd = (n->type == NBACKGND); 432 433 expredir(n->nredir.redirect); 434 INTOFF; 435 jp = makejob(n, 1); 436 if (forkshell(jp, n, backgnd ? FORK_BG : FORK_FG) == 0) { 437 INTON; 438 if (backgnd) 439 flags &=~ EV_TESTED; 440 redirect(n->nredir.redirect, 0); 441 /* never returns */ 442 evaltree(n->nredir.n, flags | EV_EXIT); 443 } 444 if (! backgnd) 445 exitstatus = waitforjob(jp); 446 INTON; 447 } 448 449 450 451 /* 452 * Compute the names of the files in a redirection list. 453 */ 454 455 STATIC void 456 expredir(union node *n) 457 { 458 union node *redir; 459 460 for (redir = n ; redir ; redir = redir->nfile.next) { 461 struct arglist fn; 462 fn.lastp = &fn.list; 463 switch (redir->type) { 464 case NFROMTO: 465 case NFROM: 466 case NTO: 467 case NCLOBBER: 468 case NAPPEND: 469 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR); 470 redir->nfile.expfname = fn.list->text; 471 break; 472 case NFROMFD: 473 case NTOFD: 474 if (redir->ndup.vname) { 475 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE); 476 fixredir(redir, fn.list->text, 1); 477 } 478 break; 479 } 480 } 481 } 482 483 484 485 /* 486 * Evaluate a pipeline. All the processes in the pipeline are children 487 * of the process creating the pipeline. (This differs from some versions 488 * of the shell, which make the last process in a pipeline the parent 489 * of all the rest.) 490 */ 491 492 STATIC void 493 evalpipe(union node *n) 494 { 495 struct job *jp; 496 struct nodelist *lp; 497 int pipelen; 498 int prevfd; 499 int pip[2]; 500 501 TRACE(("evalpipe(0x%lx) called\n", (long)n)); 502 pipelen = 0; 503 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) 504 pipelen++; 505 INTOFF; 506 jp = makejob(n, pipelen); 507 prevfd = -1; 508 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) { 509 prehash(lp->n); 510 pip[1] = -1; 511 if (lp->next) { 512 if (sh_pipe(pip) < 0) { 513 if (prevfd >= 0) 514 close(prevfd); 515 error("Pipe call failed"); 516 } 517 } 518 if (forkshell(jp, lp->n, n->npipe.backgnd ? FORK_BG : FORK_FG) == 0) { 519 INTON; 520 if (prevfd > 0) { 521 close(0); 522 copyfd(prevfd, 0); 523 close(prevfd); 524 } 525 if (pip[1] >= 0) { 526 close(pip[0]); 527 if (pip[1] != 1) { 528 close(1); 529 copyfd(pip[1], 1); 530 close(pip[1]); 531 } 532 } 533 evaltree(lp->n, EV_EXIT); 534 } 535 if (prevfd >= 0) 536 close(prevfd); 537 prevfd = pip[0]; 538 close(pip[1]); 539 } 540 if (n->npipe.backgnd == 0) { 541 exitstatus = waitforjob(jp); 542 TRACE(("evalpipe: job done exit status %d\n", exitstatus)); 543 } 544 INTON; 545 } 546 547 548 549 /* 550 * Execute a command inside back quotes. If it's a builtin command, we 551 * want to save its output in a block obtained from malloc. Otherwise 552 * we fork off a subprocess and get the output of the command via a pipe. 553 * Should be called with interrupts off. 554 */ 555 556 void 557 evalbackcmd(union node *n, struct backcmd *result) 558 { 559 int pip[2]; 560 struct job *jp; 561 struct stackmark smark; /* unnecessary */ 562 563 setstackmark(&smark); 564 result->fd = -1; 565 result->buf = NULL; 566 result->nleft = 0; 567 result->jp = NULL; 568 if (n == NULL) { 569 goto out; 570 } 571 #ifdef notyet 572 /* 573 * For now we disable executing builtins in the same 574 * context as the shell, because we are not keeping 575 * enough state to recover from changes that are 576 * supposed only to affect subshells. eg. echo "`cd /`" 577 */ 578 if (n->type == NCMD) { 579 exitstatus = oexitstatus; 580 evalcommand(n, EV_BACKCMD, result); 581 } else 582 #endif 583 { 584 INTOFF; 585 if (sh_pipe(pip) < 0) 586 error("Pipe call failed"); 587 jp = makejob(n, 1); 588 if (forkshell(jp, n, FORK_NOJOB) == 0) { 589 FORCEINTON; 590 close(pip[0]); 591 if (pip[1] != 1) { 592 close(1); 593 copyfd(pip[1], 1); 594 close(pip[1]); 595 } 596 eflag = 0; 597 evaltree(n, EV_EXIT); 598 /* NOTREACHED */ 599 } 600 close(pip[1]); 601 result->fd = pip[0]; 602 result->jp = jp; 603 INTON; 604 } 605 out: 606 popstackmark(&smark); 607 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n", 608 result->fd, result->buf, result->nleft, result->jp)); 609 } 610 611 static const char * 612 syspath(void) 613 { 614 static char *sys_path = NULL; 615 static int mib[] = {CTL_USER, USER_CS_PATH}; 616 static char def_path[] = "PATH=/usr/bin:/bin:/usr/sbin:/sbin"; 617 size_t len; 618 619 if (sys_path == NULL) { 620 if (sysctl(mib, 2, 0, &len, 0, 0) != -1 && 621 (sys_path = ckmalloc(len + 5)) != NULL && 622 sysctl(mib, 2, sys_path + 5, &len, 0, 0) != -1) { 623 memcpy(sys_path, "PATH=", 5); 624 } else { 625 ckfree(sys_path); 626 /* something to keep things happy */ 627 sys_path = def_path; 628 } 629 } 630 return sys_path; 631 } 632 633 static int 634 parse_command_args(int argc, char **argv, int *use_syspath) 635 { 636 int sv_argc = argc; 637 char *cp, c; 638 639 *use_syspath = 0; 640 641 for (;;) { 642 argv++; 643 if (--argc == 0) 644 break; 645 cp = *argv; 646 if (*cp++ != '-') 647 break; 648 if (*cp == '-' && cp[1] == 0) { 649 argv++; 650 argc--; 651 break; 652 } 653 while ((c = *cp++)) { 654 switch (c) { 655 case 'p': 656 *use_syspath = 1; 657 break; 658 default: 659 /* run 'typecmd' for other options */ 660 return 0; 661 } 662 } 663 } 664 return sv_argc - argc; 665 } 666 667 int vforked = 0; 668 669 /* 670 * Execute a simple command. 671 */ 672 673 STATIC void 674 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd) 675 { 676 struct stackmark smark; 677 union node *argp; 678 struct arglist arglist; 679 struct arglist varlist; 680 volatile int flags = flgs; 681 char ** volatile argv; 682 volatile int argc; 683 char **envp; 684 int varflag; 685 struct strlist *sp; 686 volatile int mode; 687 int pip[2]; 688 struct cmdentry cmdentry; 689 struct job * volatile jp; 690 struct jmploc jmploc; 691 struct jmploc *volatile savehandler = NULL; 692 const char *volatile savecmdname; 693 volatile struct shparam saveparam; 694 struct localvar *volatile savelocalvars; 695 volatile int e; 696 char * volatile lastarg; 697 const char * volatile path = pathval(); 698 volatile int temp_path; 699 700 vforked = 0; 701 /* First expand the arguments. */ 702 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags)); 703 setstackmark(&smark); 704 back_exitstatus = 0; 705 706 arglist.lastp = &arglist.list; 707 varflag = 1; 708 /* Expand arguments, ignoring the initial 'name=value' ones */ 709 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { 710 char *p = argp->narg.text; 711 if (varflag && is_name(*p)) { 712 do { 713 p++; 714 } while (is_in_name(*p)); 715 if (*p == '=') 716 continue; 717 } 718 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 719 varflag = 0; 720 } 721 *arglist.lastp = NULL; 722 723 expredir(cmd->ncmd.redirect); 724 725 /* Now do the initial 'name=value' ones we skipped above */ 726 varlist.lastp = &varlist.list; 727 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { 728 char *p = argp->narg.text; 729 if (!is_name(*p)) 730 break; 731 do 732 p++; 733 while (is_in_name(*p)); 734 if (*p != '=') 735 break; 736 expandarg(argp, &varlist, EXP_VARTILDE); 737 } 738 *varlist.lastp = NULL; 739 740 argc = 0; 741 for (sp = arglist.list ; sp ; sp = sp->next) 742 argc++; 743 argv = stalloc(sizeof (char *) * (argc + 1)); 744 745 for (sp = arglist.list ; sp ; sp = sp->next) { 746 TRACE(("evalcommand arg: %s\n", sp->text)); 747 *argv++ = sp->text; 748 } 749 *argv = NULL; 750 lastarg = NULL; 751 if (iflag && funcnest == 0 && argc > 0) 752 lastarg = argv[-1]; 753 argv -= argc; 754 755 /* Print the command if xflag is set. */ 756 if (xflag) { 757 char sep = 0; 758 out2str(ps4val()); 759 for (sp = varlist.list ; sp ; sp = sp->next) { 760 if (sep != 0) 761 outc(sep, &errout); 762 out2shstr(sp->text); 763 sep = ' '; 764 } 765 for (sp = arglist.list ; sp ; sp = sp->next) { 766 if (sep != 0) 767 outc(sep, &errout); 768 out2shstr(sp->text); 769 sep = ' '; 770 } 771 outc('\n', &errout); 772 flushout(&errout); 773 } 774 775 /* Now locate the command. */ 776 if (argc == 0) { 777 cmdentry.cmdtype = CMDSPLBLTIN; 778 cmdentry.u.bltin = bltincmd; 779 } else { 780 static const char PATH[] = "PATH="; 781 int cmd_flags = DO_ERR; 782 783 /* 784 * Modify the command lookup path, if a PATH= assignment 785 * is present 786 */ 787 for (sp = varlist.list; sp; sp = sp->next) 788 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) 789 path = sp->text + sizeof(PATH) - 1; 790 791 do { 792 int argsused, use_syspath; 793 find_command(argv[0], &cmdentry, cmd_flags, path); 794 if (cmdentry.cmdtype == CMDUNKNOWN) { 795 exitstatus = 127; 796 flushout(&errout); 797 goto out; 798 } 799 800 /* implement the 'command' builtin here */ 801 if (cmdentry.cmdtype != CMDBUILTIN || 802 cmdentry.u.bltin != bltincmd) 803 break; 804 cmd_flags |= DO_NOFUNC; 805 argsused = parse_command_args(argc, argv, &use_syspath); 806 if (argsused == 0) { 807 /* use 'type' builting to display info */ 808 cmdentry.u.bltin = typecmd; 809 break; 810 } 811 argc -= argsused; 812 argv += argsused; 813 if (use_syspath) 814 path = syspath() + 5; 815 } while (argc != 0); 816 if (cmdentry.cmdtype == CMDSPLBLTIN && cmd_flags & DO_NOFUNC) 817 /* posix mandates that 'command <splbltin>' act as if 818 <splbltin> was a normal builtin */ 819 cmdentry.cmdtype = CMDBUILTIN; 820 } 821 822 /* Fork off a child process if necessary. */ 823 if (cmd->ncmd.backgnd 824 || cmdentry.cmdtype == CMDNORMAL 825 || ((flags & EV_BACKCMD) != 0 826 && ((cmdentry.cmdtype != CMDBUILTIN && cmdentry.cmdtype != CMDSPLBLTIN) 827 || cmdentry.u.bltin == dotcmd 828 || cmdentry.u.bltin == evalcmd))) { 829 INTOFF; 830 jp = makejob(cmd, 1); 831 mode = cmd->ncmd.backgnd; 832 if (flags & EV_BACKCMD) { 833 mode = FORK_NOJOB; 834 if (sh_pipe(pip) < 0) 835 error("Pipe call failed"); 836 } 837 #ifdef DO_SHAREDVFORK 838 /* It is essential that if DO_SHAREDVFORK is defined that the 839 * child's address space is actually shared with the parent as 840 * we rely on this. 841 */ 842 if (cmdentry.cmdtype == CMDNORMAL) { 843 pid_t pid; 844 845 savelocalvars = localvars; 846 localvars = NULL; 847 vforked = 1; 848 switch (pid = vfork()) { 849 case -1: 850 TRACE(("Vfork failed, errno=%d\n", errno)); 851 INTON; 852 error("Cannot vfork"); 853 break; 854 case 0: 855 /* Make sure that exceptions only unwind to 856 * after the vfork(2) 857 */ 858 if (setjmp(jmploc.loc)) { 859 if (exception == EXSHELLPROC) { 860 /* We can't progress with the vfork, 861 * so, set vforked = 2 so the parent 862 * knows, and _exit(); 863 */ 864 vforked = 2; 865 _exit(0); 866 } else { 867 _exit(exerrno); 868 } 869 } 870 savehandler = handler; 871 handler = &jmploc; 872 listmklocal(varlist.list, VEXPORT | VNOFUNC); 873 forkchild(jp, cmd, mode, vforked); 874 break; 875 default: 876 handler = savehandler; /* restore from vfork(2) */ 877 poplocalvars(); 878 localvars = savelocalvars; 879 if (vforked == 2) { 880 vforked = 0; 881 882 (void)waitpid(pid, NULL, 0); 883 /* We need to progress in a normal fork fashion */ 884 goto normal_fork; 885 } 886 vforked = 0; 887 forkparent(jp, cmd, mode, pid); 888 goto parent; 889 } 890 } else { 891 normal_fork: 892 #endif 893 if (forkshell(jp, cmd, mode) != 0) 894 goto parent; /* at end of routine */ 895 FORCEINTON; 896 #ifdef DO_SHAREDVFORK 897 } 898 #endif 899 if (flags & EV_BACKCMD) { 900 if (!vforked) { 901 FORCEINTON; 902 } 903 close(pip[0]); 904 if (pip[1] != 1) { 905 close(1); 906 copyfd(pip[1], 1); 907 close(pip[1]); 908 } 909 } 910 flags |= EV_EXIT; 911 } 912 913 /* This is the child process if a fork occurred. */ 914 /* Execute the command. */ 915 switch (cmdentry.cmdtype) { 916 case CMDFUNCTION: 917 #ifdef DEBUG 918 trputs("Shell function: "); trargs(argv); 919 #endif 920 redirect(cmd->ncmd.redirect, REDIR_PUSH); 921 saveparam = shellparam; 922 shellparam.malloc = 0; 923 shellparam.reset = 1; 924 shellparam.nparam = argc - 1; 925 shellparam.p = argv + 1; 926 shellparam.optnext = NULL; 927 INTOFF; 928 savelocalvars = localvars; 929 localvars = NULL; 930 INTON; 931 if (setjmp(jmploc.loc)) { 932 if (exception == EXSHELLPROC) { 933 freeparam((volatile struct shparam *) 934 &saveparam); 935 } else { 936 freeparam(&shellparam); 937 shellparam = saveparam; 938 } 939 poplocalvars(); 940 localvars = savelocalvars; 941 handler = savehandler; 942 longjmp(handler->loc, 1); 943 } 944 savehandler = handler; 945 handler = &jmploc; 946 listmklocal(varlist.list, 0); 947 /* stop shell blowing its stack */ 948 if (++funcnest > 1000) 949 error("too many nested function calls"); 950 evaltree(cmdentry.u.func, flags & EV_TESTED); 951 funcnest--; 952 INTOFF; 953 poplocalvars(); 954 localvars = savelocalvars; 955 freeparam(&shellparam); 956 shellparam = saveparam; 957 handler = savehandler; 958 popredir(); 959 INTON; 960 if (evalskip == SKIPFUNC) { 961 evalskip = 0; 962 skipcount = 0; 963 } 964 if (flags & EV_EXIT) 965 exitshell(exitstatus); 966 break; 967 968 case CMDBUILTIN: 969 case CMDSPLBLTIN: 970 #ifdef DEBUG 971 trputs("builtin command: "); trargs(argv); 972 #endif 973 mode = (cmdentry.u.bltin == 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 } 980 e = -1; 981 savehandler = handler; 982 savecmdname = commandname; 983 handler = &jmploc; 984 if (!setjmp(jmploc.loc)) { 985 /* We need to ensure the command hash table isn't 986 * corruped by temporary PATH assignments. 987 * However we must ensure the 'local' command works! 988 */ 989 if (path != pathval() && (cmdentry.u.bltin == hashcmd || 990 cmdentry.u.bltin == typecmd)) { 991 savelocalvars = localvars; 992 localvars = 0; 993 mklocal(path - 5 /* PATH= */, 0); 994 temp_path = 1; 995 } else 996 temp_path = 0; 997 redirect(cmd->ncmd.redirect, mode); 998 999 /* exec is a special builtin, but needs this list... */ 1000 cmdenviron = varlist.list; 1001 /* we must check 'readonly' flag for all builtins */ 1002 listsetvar(varlist.list, 1003 cmdentry.cmdtype == CMDSPLBLTIN ? 0 : VNOSET); 1004 commandname = argv[0]; 1005 /* initialize nextopt */ 1006 argptr = argv + 1; 1007 optptr = NULL; 1008 /* and getopt */ 1009 optreset = 1; 1010 optind = 1; 1011 exitstatus = cmdentry.u.bltin(argc, argv); 1012 } else { 1013 e = exception; 1014 exitstatus = e == EXINT ? SIGINT + 128 : 1015 e == EXEXEC ? exerrno : 2; 1016 } 1017 handler = savehandler; 1018 flushall(); 1019 out1 = &output; 1020 out2 = &errout; 1021 freestdout(); 1022 if (temp_path) { 1023 poplocalvars(); 1024 localvars = savelocalvars; 1025 } 1026 cmdenviron = NULL; 1027 if (e != EXSHELLPROC) { 1028 commandname = savecmdname; 1029 if (flags & EV_EXIT) 1030 exitshell(exitstatus); 1031 } 1032 if (e != -1) { 1033 if ((e != EXERROR && e != EXEXEC) 1034 || cmdentry.cmdtype == CMDSPLBLTIN) 1035 exraise(e); 1036 FORCEINTON; 1037 } 1038 if (cmdentry.u.bltin != execcmd) 1039 popredir(); 1040 if (flags == EV_BACKCMD) { 1041 backcmd->buf = memout.buf; 1042 backcmd->nleft = memout.nextc - memout.buf; 1043 memout.buf = NULL; 1044 } 1045 break; 1046 1047 default: 1048 #ifdef DEBUG 1049 trputs("normal command: "); trargs(argv); 1050 #endif 1051 clearredir(vforked); 1052 redirect(cmd->ncmd.redirect, vforked ? REDIR_VFORK : 0); 1053 if (!vforked) 1054 for (sp = varlist.list ; sp ; sp = sp->next) 1055 setvareq(sp->text, VEXPORT|VSTACK); 1056 envp = environment(); 1057 shellexec(argv, envp, path, cmdentry.u.index, vforked); 1058 break; 1059 } 1060 goto out; 1061 1062 parent: /* parent process gets here (if we forked) */ 1063 if (mode == FORK_FG) { /* argument to fork */ 1064 exitstatus = waitforjob(jp); 1065 } else if (mode == FORK_NOJOB) { 1066 backcmd->fd = pip[0]; 1067 close(pip[1]); 1068 backcmd->jp = jp; 1069 } 1070 FORCEINTON; 1071 1072 out: 1073 if (lastarg) 1074 /* dsl: I think this is intended to be used to support 1075 * '_' in 'vi' command mode during line editing... 1076 * However I implemented that within libedit itself. 1077 */ 1078 setvar("_", lastarg, 0); 1079 popstackmark(&smark); 1080 } 1081 1082 1083 /* 1084 * Search for a command. This is called before we fork so that the 1085 * location of the command will be available in the parent as well as 1086 * the child. The check for "goodname" is an overly conservative 1087 * check that the name will not be subject to expansion. 1088 */ 1089 1090 STATIC void 1091 prehash(union node *n) 1092 { 1093 struct cmdentry entry; 1094 1095 if (n && n->type == NCMD && n->ncmd.args) 1096 if (goodname(n->ncmd.args->narg.text)) 1097 find_command(n->ncmd.args->narg.text, &entry, 0, 1098 pathval()); 1099 } 1100 1101 1102 1103 /* 1104 * Builtin commands. Builtin commands whose functions are closely 1105 * tied to evaluation are implemented here. 1106 */ 1107 1108 /* 1109 * No command given. 1110 */ 1111 1112 int 1113 bltincmd(int argc, char **argv) 1114 { 1115 /* 1116 * Preserve exitstatus of a previous possible redirection 1117 * as POSIX mandates 1118 */ 1119 return back_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 1134 int 1135 breakcmd(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 /* 1150 * The return command. 1151 */ 1152 1153 int 1154 returncmd(int argc, char **argv) 1155 { 1156 int ret = argc > 1 ? number(argv[1]) : exitstatus; 1157 1158 if (funcnest) { 1159 evalskip = SKIPFUNC; 1160 skipcount = 1; 1161 return ret; 1162 } 1163 else { 1164 /* Do what ksh does; skip the rest of the file */ 1165 evalskip = SKIPFILE; 1166 skipcount = 1; 1167 return ret; 1168 } 1169 } 1170 1171 1172 int 1173 falsecmd(int argc, char **argv) 1174 { 1175 return 1; 1176 } 1177 1178 1179 int 1180 truecmd(int argc, char **argv) 1181 { 1182 return 0; 1183 } 1184 1185 1186 int 1187 execcmd(int argc, char **argv) 1188 { 1189 if (argc > 1) { 1190 struct strlist *sp; 1191 1192 iflag = 0; /* exit on error */ 1193 mflag = 0; 1194 optschanged(); 1195 for (sp = cmdenviron; sp; sp = sp->next) 1196 setvareq(sp->text, VEXPORT|VSTACK); 1197 shellexec(argv + 1, environment(), pathval(), 0, 0); 1198 } 1199 return 0; 1200 } 1201 1202 static int 1203 conv_time(clock_t ticks, char *seconds, size_t l) 1204 { 1205 static clock_t tpm = 0; 1206 clock_t mins; 1207 int i; 1208 1209 if (!tpm) 1210 tpm = sysconf(_SC_CLK_TCK) * 60; 1211 1212 mins = ticks / tpm; 1213 snprintf(seconds, l, "%.4f", (ticks - mins * tpm) * 60.0 / tpm ); 1214 1215 if (seconds[0] == '6' && seconds[1] == '0') { 1216 /* 59.99995 got rounded up... */ 1217 mins++; 1218 strlcpy(seconds, "0.0", l); 1219 return mins; 1220 } 1221 1222 /* suppress trailing zeros */ 1223 i = strlen(seconds) - 1; 1224 for (; seconds[i] == '0' && seconds[i - 1] != '.'; i--) 1225 seconds[i] = 0; 1226 return mins; 1227 } 1228 1229 int 1230 timescmd(int argc, char **argv) 1231 { 1232 struct tms tms; 1233 int u, s, cu, cs; 1234 char us[8], ss[8], cus[8], css[8]; 1235 1236 nextopt(""); 1237 1238 times(&tms); 1239 1240 u = conv_time(tms.tms_utime, us, sizeof(us)); 1241 s = conv_time(tms.tms_stime, ss, sizeof(ss)); 1242 cu = conv_time(tms.tms_cutime, cus, sizeof(cus)); 1243 cs = conv_time(tms.tms_cstime, css, sizeof(css)); 1244 1245 outfmt(out1, "%dm%ss %dm%ss\n%dm%ss %dm%ss\n", 1246 u, us, s, ss, cu, cus, cs, css); 1247 1248 return 0; 1249 } 1250