1 /* $NetBSD: eval.c,v 1.202 2026/11/24 13:25:53 kre 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.202 2026/11/24 13:25:53 kre 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 <string.h> 49 #include <errno.h> 50 #include <limits.h> 51 #include <unistd.h> 52 #include <fcntl.h> 53 #include <sys/stat.h> 54 #include <sys/times.h> 55 #include <sys/param.h> 56 #include <sys/types.h> 57 #include <sys/wait.h> 58 #include <sys/sysctl.h> 59 60 /* 61 * Evaluate a command. 62 */ 63 64 #include "shell.h" 65 #include "nodes.h" 66 #include "syntax.h" 67 #include "expand.h" 68 #include "parser.h" 69 #include "jobs.h" 70 #include "eval.h" 71 #include "builtins.h" 72 #include "options.h" 73 #include "exec.h" 74 #include "redir.h" 75 #include "input.h" 76 #include "output.h" 77 #include "trap.h" 78 #include "var.h" 79 #include "memalloc.h" 80 #include "error.h" 81 #include "show.h" 82 #include "mystring.h" 83 #include "main.h" 84 #ifndef SMALL 85 #include "nodenames.h" 86 #include "myhistedit.h" 87 #endif 88 89 90 STATIC struct skipsave s_k_i_p; 91 #define evalskip (s_k_i_p.state) 92 #define skipcount (s_k_i_p.count) 93 94 STATIC int loopnest; /* current loop nesting level */ 95 STATIC int funcnest; /* depth of function calls */ 96 STATIC int builtin_flags; /* evalcommand flags for builtins */ 97 /* 98 * Base function nesting level inside a dot command. Set to 0 initially 99 * and to (funcnest + 1) before every dot command to enable 100 * 1) detection of being in a file sourced by a dot command and 101 * 2) counting of function nesting in that file for the implementation 102 * of the return command. 103 * The value is reset to its previous value after the dot command. 104 */ 105 STATIC int dot_funcnest; 106 107 108 const char *commandname; 109 struct strlist *cmdenviron; 110 int exitstatus; /* exit status of last command */ 111 int back_exitstatus; /* exit status of backquoted command */ 112 113 114 STATIC void evalloop(union node *, int); 115 STATIC void evalfor(union node *, int); 116 STATIC void evalcase(union node *, int); 117 STATIC void evalsubshell(union node *, int); 118 STATIC void expredir(union node *); 119 STATIC void evalredir(union node *, int); 120 STATIC void evalpipe(union node *); 121 STATIC void evalcommand(union node *, int, struct backcmd *); 122 STATIC void prehash(union node *); 123 124 STATIC char *find_dot_file(char *); 125 126 /* 127 * Called to reset things after an exception. 128 */ 129 130 #ifdef mkinit 131 INCLUDE "eval.h" 132 133 RESET { 134 reset_eval(); 135 } 136 137 SHELLPROC { 138 exitstatus = 0; 139 } 140 #endif 141 142 void 143 reset_eval(void) 144 { 145 evalskip = SKIPNONE; 146 dot_funcnest = 0; 147 loopnest = 0; 148 funcnest = 0; 149 } 150 151 static int 152 sh_pipe(int fds[2]) 153 { 154 int nfd; 155 156 if (pipe(fds)) 157 return -1; 158 159 if (fds[0] < 3) { 160 nfd = fcntl(fds[0], F_DUPFD, 3); 161 if (nfd != -1) { 162 close(fds[0]); 163 fds[0] = nfd; 164 } 165 } 166 167 if (fds[1] < 3) { 168 nfd = fcntl(fds[1], F_DUPFD, 3); 169 if (nfd != -1) { 170 close(fds[1]); 171 fds[1] = nfd; 172 } 173 } 174 return 0; 175 } 176 177 178 /* 179 * The eval command. 180 */ 181 182 int 183 evalcmd(int argc, char **argv) 184 { 185 char *p; 186 char *concat; 187 char **ap; 188 189 if (argc > 1) { 190 p = argv[1]; 191 if (argc > 2) { 192 STARTSTACKSTR(concat); 193 ap = argv + 2; 194 for (;;) { 195 while (*p) 196 STPUTC(*p++, concat); 197 if ((p = *ap++) == NULL) 198 break; 199 STPUTC(' ', concat); 200 } 201 STPUTC('\0', concat); 202 p = grabstackstr(concat); 203 } 204 evalstring(p, builtin_flags & EV_TESTED); 205 } else 206 exitstatus = 0; 207 return exitstatus; 208 } 209 210 211 /* 212 * Execute a command or commands contained in a string. 213 */ 214 215 void 216 evalstring(const char *s, int flag) 217 { 218 union node *n; 219 struct stackmark smark; 220 int last; 221 int any; 222 223 last = flag & EV_EXIT; 224 flag &= ~EV_EXIT; 225 226 setstackmark(&smark); 227 setinputstring(s, 1, line_number); 228 229 any = 0; /* to determine if exitstatus will have been set */ 230 while ((n = parsecmd(0)) != NEOF) { 231 XTRACE(DBG_EVAL, ("evalstring: "), showtree(n)); 232 if (n && nflag == 0) { 233 if (last && at_eof()) 234 evaltree(n, flag | EV_EXIT); 235 else 236 evaltree(n, flag); 237 any = 1; 238 if (evalskip) 239 break; 240 } 241 rststackmark(&smark); 242 } 243 popfile(); 244 popstackmark(&smark); 245 if (!any) 246 exitstatus = 0; 247 if (last) 248 exraise(EXEXIT); 249 } 250 251 252 253 /* 254 * Evaluate a parse tree. The value is left in the global variable 255 * exitstatus. 256 */ 257 258 void 259 evaltree(union node *n, int flags) 260 { 261 bool do_etest; 262 int sflags = flags & ~EV_EXIT; 263 union node *next; 264 struct stackmark smark; 265 266 do_etest = false; 267 if (n == NULL || nflag) { 268 VTRACE(DBG_EVAL, ("evaltree(%s) called\n", 269 n == NULL ? "NULL" : "-n")); 270 if (nflag == 0) 271 exitstatus = 0; 272 goto out2; 273 } 274 275 setstackmark(&smark); 276 do { 277 #ifndef SMALL 278 displayhist = 1; /* show history substitutions done with fc */ 279 #endif 280 next = NULL; 281 CTRACE(DBG_EVAL, 282 ("pid %d, evaltree(%p: %s(%d), %#x S:%#x) called%s\n", 283 getpid(), n, NODETYPENAME(n->type), n->type, flags, sflags, 284 do_etest ? " ET" : "")); 285 /* 286 if (n->type != NCMD && traps_invalid) 287 free_traps(); 288 */ 289 switch (n->type) { 290 case NSEMI: 291 evaltree(n->nbinary.ch1, sflags); 292 if (nflag || evalskip) 293 goto out1; 294 next = n->nbinary.ch2; 295 break; 296 case NAND: 297 evaltree(n->nbinary.ch1, EV_TESTED); 298 if (nflag || evalskip || exitstatus != 0) 299 goto out1; 300 next = n->nbinary.ch2; 301 break; 302 case NOR: 303 evaltree(n->nbinary.ch1, EV_TESTED); 304 if (nflag || evalskip || exitstatus == 0) 305 goto out1; 306 next = n->nbinary.ch2; 307 break; 308 case NREDIR: 309 if (traps_invalid) 310 free_traps(); 311 evalredir(n, flags); 312 break; 313 case NSUBSHELL: 314 evalsubshell(n, flags); 315 do_etest = !(flags & EV_TESTED); 316 break; 317 case NBACKGND: 318 if (traps_invalid) 319 free_traps(); 320 evalsubshell(n, flags); 321 break; 322 case NIF: { 323 if (traps_invalid) 324 free_traps(); 325 evaltree(n->nif.test, EV_TESTED); 326 if (nflag || evalskip) 327 goto out1; 328 if (exitstatus == 0) 329 next = n->nif.ifpart; 330 else if (n->nif.elsepart) 331 next = n->nif.elsepart; 332 else 333 exitstatus = 0; 334 break; 335 } 336 case NWHILE: 337 case NUNTIL: 338 if (traps_invalid) 339 free_traps(); 340 evalloop(n, sflags); 341 break; 342 case NFOR: 343 if (traps_invalid) 344 free_traps(); 345 evalfor(n, sflags); 346 break; 347 case NCASE: 348 if (traps_invalid) 349 free_traps(); 350 evalcase(n, sflags); 351 break; 352 case NDEFUN: 353 if (traps_invalid) 354 free_traps(); 355 CTRACE(DBG_EVAL, ("Defining fn %s @%d%s\n", 356 n->narg.text, n->narg.lineno, 357 fnline1 ? " LINENO=1" : "")); 358 defun(n->narg.text, n->narg.next, n->narg.lineno); 359 exitstatus = 0; 360 break; 361 case NNOT: 362 evaltree(n->nnot.com, EV_TESTED); 363 exitstatus = !exitstatus; 364 break; 365 case NDNOT: 366 evaltree(n->nnot.com, EV_TESTED); 367 if (exitstatus != 0) 368 exitstatus = 1; 369 break; 370 case NPIPE: 371 if (traps_invalid) 372 free_traps(); 373 evalpipe(n); 374 do_etest = !(flags & EV_TESTED); 375 break; 376 case NCMD: 377 evalcommand(n, flags, NULL); 378 do_etest = !(flags & EV_TESTED); 379 break; 380 default: 381 #ifdef NODETYPENAME 382 out1fmt("Node type = %d(%s)\n", 383 n->type, NODETYPENAME(n->type)); 384 #else 385 out1fmt("Node type = %d\n", n->type); 386 #endif 387 flushout(&output); 388 break; 389 } 390 n = next; 391 rststackmark(&smark); 392 } while (n != NULL); 393 out1:; 394 popstackmark(&smark); 395 out2:; 396 if (pendingsigs) 397 dotrap(); 398 if (eflag && exitstatus != 0 && do_etest) { 399 CTRACE(DBG_EVAL, ("evaltree() -e exit(%d)\n", exitstatus)); 400 exitshell(exitstatus); 401 } 402 if (flags & EV_EXIT) 403 exraise(EXEXIT); 404 } 405 406 407 STATIC void 408 evalloop(union node *n, int flags) 409 { 410 int status; 411 412 loopnest++; 413 status = 0; 414 415 CTRACE(DBG_EVAL, ("evalloop %s:", NODETYPENAME(n->type))); 416 VXTRACE(DBG_EVAL, (" "), showtree(n->nbinary.ch1)); 417 VXTRACE(DBG_EVAL, ("evalloop do: "), showtree(n->nbinary.ch2)); 418 VTRACE(DBG_EVAL, ("evalloop done\n")); 419 CTRACE(DBG_EVAL, ("\n")); 420 421 for (;;) { 422 evaltree(n->nbinary.ch1, EV_TESTED); 423 if (nflag) 424 break; 425 if (evalskip) { 426 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { 427 evalskip = SKIPNONE; 428 continue; 429 } 430 if (evalskip == SKIPBREAK && --skipcount <= 0) 431 evalskip = SKIPNONE; 432 if (evalskip == SKIPFUNC || evalskip == SKIPFILE) 433 status = exitstatus; 434 break; 435 } 436 if (n->type == NWHILE) { 437 if (exitstatus != 0) 438 break; 439 } else { 440 if (exitstatus == 0) 441 break; 442 } 443 evaltree(n->nbinary.ch2, flags & EV_TESTED); 444 status = exitstatus; 445 if (evalskip) 446 goto skipping; 447 } 448 loopnest--; 449 exitstatus = status; 450 } 451 452 453 454 STATIC void 455 evalfor(union node *n, int flags) 456 { 457 struct arglist arglist; 458 union node *argp; 459 struct strlist *sp; 460 struct stackmark smark; 461 int status; 462 463 status = nflag ? exitstatus : 0; 464 465 setstackmark(&smark); 466 arglist.lastp = &arglist.list; 467 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { 468 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 469 if (evalskip) 470 goto out; 471 } 472 *arglist.lastp = NULL; 473 474 loopnest++; 475 for (sp = arglist.list ; sp ; sp = sp->next) { 476 line_number = n->nfor.lineno; 477 if (xflag) { 478 outxstr(expandstr(ps4val(), line_number)); 479 outxstr("for "); 480 outxstr(n->nfor.var); 481 outxc('='); 482 outxshstr(sp->text); 483 outxc('\n'); 484 flushout(outx); 485 } 486 487 setvar(n->nfor.var, sp->text, 0); 488 evaltree(n->nfor.body, flags & EV_TESTED); 489 status = exitstatus; 490 if (nflag) 491 break; 492 if (evalskip) { 493 if (evalskip == SKIPCONT && --skipcount <= 0) { 494 evalskip = SKIPNONE; 495 continue; 496 } 497 if (evalskip == SKIPBREAK && --skipcount <= 0) 498 evalskip = SKIPNONE; 499 break; 500 } 501 } 502 loopnest--; 503 exitstatus = status; 504 out:; 505 popstackmark(&smark); 506 } 507 508 509 510 STATIC void 511 evalcase(union node *n, int flags) 512 { 513 union node *cp, *ncp; 514 union node *patp; 515 struct arglist arglist; 516 struct stackmark smark; 517 int status = 0; 518 519 setstackmark(&smark); 520 arglist.lastp = &arglist.list; 521 line_number = n->ncase.lineno; 522 expandarg(n->ncase.expr, &arglist, EXP_TILDE); 523 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) { 524 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) { 525 line_number = patp->narg.lineno; 526 if (casematch(patp, arglist.list->text)) { 527 while (cp != NULL && evalskip == 0 && 528 nflag == 0) { 529 if (cp->type == NCLISTCONT) 530 ncp = cp->nclist.next; 531 else 532 ncp = NULL; 533 line_number = cp->nclist.lineno; 534 evaltree(cp->nclist.body, flags); 535 status = exitstatus; 536 cp = ncp; 537 } 538 goto out; 539 } 540 } 541 } 542 out:; 543 exitstatus = status; 544 popstackmark(&smark); 545 } 546 547 548 549 /* 550 * Kick off a subshell to evaluate a tree. 551 */ 552 553 STATIC void 554 evalsubshell(union node *n, int flags) 555 { 556 struct job *jp= NULL; 557 int backgnd = (n->type == NBACKGND); 558 559 expredir(n->nredir.redirect); 560 if (xflag && n->nredir.redirect) { 561 union node *rn; 562 563 outxstr(expandstr(ps4val(), line_number)); 564 outxstr("using redirections:"); 565 for (rn = n->nredir.redirect; rn; rn = rn->nfile.next) 566 (void) outredir(outx, rn, ' '); 567 outxstr(" do subshell ("/*)*/); 568 if (backgnd) 569 outxstr(/*(*/") &"); 570 outxc('\n'); 571 flushout(outx); 572 } 573 INTOFF; 574 if ((!backgnd && flags & EV_EXIT && !have_traps() && !anyjobs()) || 575 forkshell(jp = makejob(n, 1), n, backgnd?FORK_BG:FORK_FG) == 0) { 576 if (backgnd) 577 flags &=~ EV_TESTED; 578 INTON; 579 redirect(n->nredir.redirect, REDIR_KEEP); 580 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */ 581 } else if (backgnd) { 582 jobstarted(jp); 583 exitstatus = 0; 584 } else 585 exitstatus = waitforjob(jp); 586 INTON; 587 588 if (!backgnd && xflag && n->nredir.redirect) { 589 outxstr(expandstr(ps4val(), line_number)); 590 outxstr(/*(*/") done subshell\n"); 591 flushout(outx); 592 } 593 } 594 595 596 597 /* 598 * Compute the names of the files in a redirection list. 599 */ 600 601 STATIC void 602 expredir(union node *n) 603 { 604 union node *redir; 605 606 for (redir = n ; redir ; redir = redir->nfile.next) { 607 struct arglist fn; 608 609 fn.lastp = &fn.list; 610 switch (redir->type) { 611 case NFROMTO: 612 case NFROM: 613 case NTO: 614 case NCLOBBER: 615 case NAPPEND: 616 expandarg(redir->nfile.fname, &fn, 617 EXP_TILDE | EXP_REDIR); 618 redir->nfile.expfname = fn.list->text; 619 break; 620 case NFROMFD: 621 case NTOFD: 622 if (redir->ndup.vname) { 623 expandarg(redir->ndup.vname, &fn, 624 EXP_TILDE | EXP_REDIR); 625 fixredir(redir, fn.list->text, 1); 626 } 627 break; 628 case NHERE: 629 redir->nhere.text = redir->nhere.doc->narg.text; 630 break; 631 case NXHERE: 632 redir->nhere.text = expandhere(redir->nhere.doc); 633 break; 634 } 635 } 636 } 637 638 /* 639 * Perform redirections for a compound command, and then do it (and restore) 640 */ 641 STATIC void 642 evalredir(union node *n, int flags) 643 { 644 struct jmploc jmploc; 645 struct jmploc * const savehandler = handler; 646 volatile int in_redirect = 1; 647 const char * volatile PS4 = NULL; 648 649 expredir(n->nredir.redirect); 650 651 if (xflag && n->nredir.redirect) { 652 union node *rn; 653 654 outxstr(PS4 = expandstr(ps4val(), line_number)); 655 outxstr("using redirections:"); 656 for (rn = n->nredir.redirect; rn != NULL; rn = rn->nfile.next) 657 (void) outredir(outx, rn, ' '); 658 outxstr(" do {\n"); /* } */ 659 flushout(outx); 660 } 661 662 if (setjmp(jmploc.loc)) { 663 int e; 664 665 handler = savehandler; 666 e = exception; 667 popredir(POPREDIR_UNDO); 668 if (PS4 != NULL) { 669 outxstr(PS4); 670 /* { */ outxstr("} failed\n"); 671 flushout(outx); 672 } 673 if (e == EXERROR || e == EXEXEC) { 674 if (in_redirect) { 675 exitstatus = 2; 676 return; 677 } 678 } 679 longjmp(handler->loc, 1); 680 } else { 681 INTOFF; 682 handler = &jmploc; 683 redirect(n->nredir.redirect, REDIR_PUSH | REDIR_KEEP); 684 in_redirect = 0; 685 INTON; 686 evaltree(n->nredir.n, flags); 687 } 688 INTOFF; 689 handler = savehandler; 690 popredir(POPREDIR_UNDO); 691 INTON; 692 693 if (PS4 != NULL) { 694 outxstr(PS4); 695 /* { */ outxstr("} done\n"); 696 flushout(outx); 697 } 698 } 699 700 701 /* 702 * Evaluate a pipeline. All the processes in the pipeline are children 703 * of the process creating the pipeline. (This differs from some versions 704 * of the shell, which make the last process in a pipeline the parent 705 * of all the rest.) 706 */ 707 708 STATIC void 709 evalpipe(union node *n) 710 { 711 struct job *jp; 712 struct nodelist *lp; 713 int pipelen; 714 int prevfd; 715 int pip[2]; 716 717 CTRACE(DBG_EVAL, ("evalpipe(%p) called\n", n)); 718 pipelen = 0; 719 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) 720 pipelen++; 721 INTOFF; 722 jp = makejob(n, pipelen); 723 prevfd = -1; 724 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) { 725 prehash(lp->n); 726 pip[1] = -1; 727 if (lp->next) { 728 if (sh_pipe(pip) < 0) { 729 if (prevfd >= 0) 730 close(prevfd); 731 error("Pipe call failed: %s", strerror(errno)); 732 } 733 } 734 if (forkshell(jp, lp->n, 735 n->npipe.backgnd ? FORK_BG : FORK_FG) == 0) { 736 INTON; 737 if (prevfd > 0) 738 movefd(prevfd, 0); 739 if (pip[1] >= 0) { 740 close(pip[0]); 741 movefd(pip[1], 1); 742 } 743 evaltree(lp->n, EV_EXIT); 744 } 745 if (prevfd >= 0) 746 close(prevfd); 747 prevfd = pip[0]; 748 close(pip[1]); 749 } 750 if (n->npipe.backgnd == 0) { 751 exitstatus = waitforjob(jp); 752 CTRACE(DBG_EVAL, ("evalpipe: job done exit status %d\n", 753 exitstatus)); 754 } else { 755 jobstarted(jp); 756 exitstatus = 0; 757 } 758 INTON; 759 } 760 761 762 763 /* 764 * Execute a command inside back quotes. If it's a builtin command, we 765 * want to save its output in a block obtained from malloc. Otherwise 766 * we fork off a subprocess and get the output of the command via a pipe. 767 * Should be called with interrupts off. 768 */ 769 770 void 771 evalbackcmd(union node *n, struct backcmd *result) 772 { 773 int pip[2]; 774 struct job *jp; 775 struct stackmark smark; /* unnecessary (because we fork) */ 776 777 result->fd = -1; 778 result->buf = NULL; 779 result->nleft = 0; 780 result->jp = NULL; 781 782 if (nflag || n == NULL) 783 goto out; 784 785 setstackmark(&smark); 786 787 #ifdef notyet 788 /* 789 * For now we disable executing builtins in the same 790 * context as the shell, because we are not keeping 791 * enough state to recover from changes that are 792 * supposed only to affect subshells. eg. echo "`cd /`" 793 */ 794 if (n->type == NCMD) { 795 exitstatus = oexitstatus; /* XXX o... no longer exists */ 796 evalcommand(n, EV_BACKCMD, result); 797 } else 798 #endif 799 { 800 INTOFF; 801 if (sh_pipe(pip) < 0) 802 error("Pipe call failed"); 803 jp = makejob(n, 0); /* 0 --> leave jobs_invalid, no jobctl */ 804 if (forkshell(jp, n, FORK_NOJOB) == 0) { 805 FORCEINTON; 806 close(pip[0]); 807 movefd(pip[1], 1); 808 evaltree(n, EV_EXIT); 809 /* NOTREACHED */ 810 } 811 close(pip[1]); 812 result->fd = pip[0]; 813 result->jp = jp; 814 INTON; 815 } 816 popstackmark(&smark); 817 out:; 818 CTRACE(DBG_EVAL, ("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n", 819 result->fd, result->buf, result->nleft, result->jp)); 820 } 821 822 const char * 823 syspath(void) 824 { 825 static char *sys_path = NULL; 826 static int mib[] = {CTL_USER, USER_CS_PATH}; 827 static char def_path[] = "PATH=/usr/bin:/bin:/usr/sbin:/sbin"; 828 size_t len; 829 830 if (sys_path == NULL) { 831 if (sysctl(mib, 2, 0, &len, 0, 0) != -1 && 832 (sys_path = ckmalloc(len + 5)) != NULL && 833 sysctl(mib, 2, sys_path + 5, &len, 0, 0) != -1) { 834 memcpy(sys_path, "PATH=", 5); 835 } else { 836 ckfree(sys_path); 837 /* something to keep things happy */ 838 sys_path = def_path; 839 } 840 } 841 return sys_path; 842 } 843 844 static int 845 parse_command_args(int argc, char **argv, int *use_syspath) 846 { 847 int sv_argc = argc; 848 char *cp, c; 849 850 *use_syspath = 0; 851 852 for (;;) { 853 argv++; 854 if (--argc == 0) 855 break; 856 cp = *argv; 857 if (*cp++ != '-') 858 break; 859 if (*cp == '-' && cp[1] == 0) { 860 argv++; 861 argc--; 862 break; 863 } 864 while ((c = *cp++)) { 865 switch (c) { 866 case 'p': 867 *use_syspath = 1; 868 break; 869 default: 870 /* run 'typecmd' for other options */ 871 return 0; 872 } 873 } 874 } 875 return sv_argc - argc; 876 } 877 878 volatile int vforking = 0; 879 880 /* 881 * Execute a simple command. 882 */ 883 884 STATIC void 885 evalcommand(union node *cmd, int flgs, struct backcmd *backcmd) 886 { 887 struct stackmark smark; 888 union node *argp; 889 struct arglist arglist; 890 struct arglist varlist; 891 volatile int flags = flgs; 892 char ** volatile argv; 893 volatile int argc; 894 char **envp; 895 int varflag; 896 struct strlist *sp; 897 volatile int mode; 898 int pip[2]; 899 struct cmdentry cmdentry; 900 struct job * volatile jp; 901 struct jmploc jmploc; 902 struct jmploc *volatile savehandler = NULL; 903 const char *volatile savecmdname; 904 volatile struct shparam saveparam; 905 struct localvar *volatile savelocalvars; 906 struct parsefile *volatile savetopfile; 907 volatile int e; 908 char * volatile lastarg; 909 const char * volatile path = pathval(); 910 volatile int temp_path; 911 const int savefuncline = funclinebase; 912 const int savefuncabs = funclineabs; 913 volatile int cmd_flags = 0; 914 915 vforking = 0; 916 /* First expand the arguments. */ 917 CTRACE(DBG_EVAL, ("evalcommand(%p, %d) called [%s]\n", cmd, flags, 918 cmd->ncmd.args ? cmd->ncmd.args->narg.text : "")); 919 setstackmark(&smark); 920 back_exitstatus = 0; 921 922 line_number = cmd->ncmd.lineno; 923 924 arglist.lastp = &arglist.list; 925 varflag = 1; 926 /* Expand arguments, ignoring the initial 'name=value' ones */ 927 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { 928 if (varflag && isassignment(argp->narg.text)) 929 continue; 930 varflag = 0; 931 line_number = argp->narg.lineno; 932 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); 933 } 934 *arglist.lastp = NULL; 935 936 expredir(cmd->ncmd.redirect); 937 938 /* Now do the initial 'name=value' ones we skipped above */ 939 varlist.lastp = &varlist.list; 940 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { 941 line_number = argp->narg.lineno; 942 if (!isassignment(argp->narg.text)) 943 break; 944 /* EXP_CASE handles CTL* chars in expansions properly */ 945 expandarg(argp, &varlist, EXP_VARTILDE | EXP_CASE); 946 } 947 *varlist.lastp = NULL; 948 949 argc = 0; 950 for (sp = arglist.list ; sp ; sp = sp->next) 951 argc++; 952 argv = stalloc(sizeof (char *) * (argc + 1)); 953 954 for (sp = arglist.list ; sp ; sp = sp->next) { 955 VTRACE(DBG_EVAL, ("evalcommand arg: %s\n", sp->text)); 956 *argv++ = sp->text; 957 } 958 *argv = NULL; 959 lastarg = NULL; 960 if (iflag && funcnest == 0 && argc > 0) 961 lastarg = argv[-1]; 962 argv -= argc; 963 964 /* Print the command if xflag is set. */ 965 if (xflag) { 966 char sep = 0; 967 union node *rn; 968 969 outxstr(expandstr(ps4val(), line_number)); 970 for (sp = varlist.list ; sp ; sp = sp->next) { 971 char *p; 972 973 if (sep != 0) 974 outxc(sep); 975 976 /* 977 * The "var=" part should not be quoted, regardless 978 * of the value, or it would not represent an 979 * assignment, but rather a command 980 */ 981 p = strchr(sp->text, '='); 982 if (p != NULL) { 983 *p = '\0'; /*XXX*/ 984 outxshstr(sp->text); 985 outxc('='); 986 *p++ = '='; /*XXX*/ 987 } else 988 p = sp->text; 989 outxshstr(p); 990 sep = ' '; 991 } 992 for (sp = arglist.list ; sp ; sp = sp->next) { 993 if (sep != 0) 994 outxc(sep); 995 outxshstr(sp->text); 996 sep = ' '; 997 } 998 for (rn = cmd->ncmd.redirect; rn; rn = rn->nfile.next) 999 if (outredir(outx, rn, sep)) 1000 sep = ' '; 1001 outxc('\n'); 1002 flushout(outx); 1003 } 1004 1005 /* Now locate the command. */ 1006 if (argc == 0) { 1007 /* 1008 * the empty command begins as a normal builtin, and 1009 * remains that way while redirects are processed, then 1010 * will become special before we get to doing the 1011 * var assigns. 1012 */ 1013 cmdentry.cmdtype = CMDBUILTIN; 1014 cmdentry.u.bltin = bltincmd; 1015 VTRACE(DBG_CMDS, ("No command name, assume \"command\"\n")); 1016 } else { 1017 static const char PATH[] = "PATH="; 1018 1019 /* 1020 * Modify the command lookup path, if a PATH= assignment 1021 * is present 1022 */ 1023 for (sp = varlist.list; sp; sp = sp->next) 1024 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) 1025 path = sp->text + sizeof(PATH) - 1; 1026 1027 do { 1028 int argsused, use_syspath; 1029 1030 find_command(argv[0], &cmdentry, cmd_flags, path); 1031 VTRACE(DBG_CMDS, ("Command %s type %d\n", argv[0], 1032 cmdentry.cmdtype)); 1033 #if 0 1034 /* 1035 * This short circuits all of the processing that 1036 * should be done (including processing the 1037 * redirects), so just don't ... 1038 * 1039 * (eventually this whole #if'd block will vanish) 1040 */ 1041 if (cmdentry.cmdtype == CMDUNKNOWN) { 1042 exitstatus = 127; 1043 flushout(&errout); 1044 goto out; 1045 } 1046 #endif 1047 1048 /* implement the 'command' builtin here */ 1049 if (cmdentry.cmdtype != CMDBUILTIN || 1050 cmdentry.u.bltin != bltincmd) 1051 break; 1052 VTRACE(DBG_CMDS, ("Command \"command\"\n")); 1053 cmd_flags |= DO_NOFUNC; 1054 argsused = parse_command_args(argc, argv, &use_syspath); 1055 if (argsused == 0) { 1056 /* use 'type' builtin to display info */ 1057 VTRACE(DBG_CMDS, 1058 ("Command \"command\" -> \"type\"\n")); 1059 cmdentry.u.bltin = typecmd; 1060 break; 1061 } 1062 argc -= argsused; 1063 argv += argsused; 1064 if (use_syspath) 1065 path = syspath() + 5; 1066 } while (argc != 0); 1067 if (cmdentry.cmdtype == CMDSPLBLTIN && cmd_flags & DO_NOFUNC) 1068 /* posix mandates that 'command <splbltin>' act as if 1069 <splbltin> was a normal builtin */ 1070 cmdentry.cmdtype = CMDBUILTIN; 1071 } 1072 1073 /* 1074 * When traps are invalid, we permit the following: 1075 * trap 1076 * command trap 1077 * eval trap 1078 * command eval trap 1079 * eval command trap 1080 * without zapping the traps completely, in all other cases we do. 1081 * Function calls also do not zap the traps (but commands they execute 1082 * probably will) - this allows a function like 1083 * trapstate() { trap -p; } 1084 * called as save_traps=$(trapstate). 1085 * 1086 * The test here permits eval "anything" but when evalstring() comes 1087 * back here again, the "anything" will be validated. 1088 * This means we can actually do: 1089 * eval eval eval command eval eval command trap 1090 * as long as we end up with just "trap" 1091 * 1092 * We permit "command" by allowing CMDBUILTIN as well as CMDSPLBLTIN 1093 * 1094 * trapcmd() takes care of doing free_traps() if it is needed there. 1095 */ 1096 if (traps_invalid && 1097 cmdentry.cmdtype != CMDFUNCTION && 1098 ((cmdentry.cmdtype!=CMDSPLBLTIN && cmdentry.cmdtype!=CMDBUILTIN) || 1099 (cmdentry.u.bltin != trapcmd && cmdentry.u.bltin != evalcmd))) 1100 free_traps(); 1101 1102 /* Fork off a child process if necessary. */ 1103 if (cmd->ncmd.backgnd 1104 || ((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN) 1105 && (have_traps() || (flags & EV_EXIT) == 0)) 1106 #ifdef notyet /* EV_BACKCMD is never set currently */ 1107 /* this will need more work if/when it gets used */ 1108 || ((flags & EV_BACKCMD) != 0 1109 && (cmdentry.cmdtype != CMDBUILTIN 1110 && cmdentry.cmdtype != CMDSPLBLTIN) 1111 || cmdentry.u.bltin == dotcmd 1112 || cmdentry.u.bltin == evalcmd) 1113 #endif 1114 ) { 1115 INTOFF; 1116 jp = makejob(cmd, 1); 1117 mode = cmd->ncmd.backgnd; 1118 if (flags & EV_BACKCMD) { 1119 mode = FORK_NOJOB; 1120 if (sh_pipe(pip) < 0) 1121 error("Pipe call failed"); 1122 } 1123 #ifdef DO_SHAREDVFORK 1124 /* It is essential that if DO_SHAREDVFORK is defined that the 1125 * child's address space is actually shared with the parent as 1126 * we rely on this. 1127 */ 1128 if (usefork == 0 && cmdentry.cmdtype == CMDNORMAL && 1129 (!cmd->ncmd.backgnd || cmd->ncmd.redirect == NULL)) { 1130 pid_t pid; 1131 int serrno; 1132 sigset_t block_all, olds; 1133 1134 (void)sigfillset(&block_all); 1135 savelocalvars = localvars; 1136 localvars = NULL; 1137 1138 /* see jobs.c:forkshell() for explanation */ 1139 (void)sigprocmask(SIG_BLOCK, &block_all, &olds); 1140 vforking = 1; 1141 VFORK_BLOCK 1142 switch (pid = vfork()) { 1143 case -1: 1144 serrno = errno; 1145 vforking = 0; 1146 (void)sigprocmask(SIG_SETMASK, &olds, NULL); 1147 VTRACE(DBG_EVAL, ("vfork() failed, errno=%d\n", 1148 serrno)); 1149 INTON; 1150 error("Cannot vfork (%s)", strerror(serrno)); 1151 break; 1152 case 0: 1153 /* 1154 * Make sure that exceptions only unwind to 1155 * after the vfork(2) 1156 */ 1157 SHELL_FORKED(); 1158 if (setjmp(jmploc.loc)) { 1159 VTRACE(DBG_EVAL|DBG_ERRS| 1160 DBG_PROCS|DBG_CMDS|DBG_TRAP, 1161 ("vfork child exit exception:%d " 1162 "exitstatus:%d exerrno:%d\n", 1163 exception, exitstatus, exerrno)); 1164 1165 if (exception == EXSHELLPROC) { 1166 /* 1167 * We can't progress with the 1168 * vfork, so, set vforking = 2 1169 * so the parent knows, 1170 * and _exit(); 1171 */ 1172 vforking = 2; 1173 _exit(0); 1174 } else { 1175 _exit(exception == EXEXIT ? 1176 exitstatus : exerrno); 1177 } 1178 } 1179 savehandler = handler; 1180 handler = &jmploc; 1181 listmklocal(varlist.list, 1182 VDOEXPORT | VEXPORT | VNOFUNC); 1183 forkchild(jp, cmd, mode, vforking, &olds); 1184 break; 1185 default: 1186 VFORK_UNDO(); 1187 /* restore from vfork(2) */ 1188 /* 1189 * We need to know what happened to the 1190 * vfork() (currently in vforking) but 1191 * we need to restore signals asap, and 1192 * vforking cannot remain set after that. 1193 * so ... 1194 */ 1195 { 1196 int vforkresult = vforking; 1197 1198 vforking = 0; 1199 (void)sigprocmask(SIG_SETMASK, &olds, NULL); 1200 1201 CTRACE(DBG_PROCS|DBG_CMDS, 1202 ("parent after vfork - vforking=%d\n", 1203 vforkresult)); 1204 1205 handler = savehandler; 1206 poplocalvars(); 1207 localvars = savelocalvars; 1208 if (vforkresult == 2) { 1209 /* 1210 * obliterate the deceased zombie 1211 * (known to have exited already) 1212 */ 1213 (void)waitpid(pid, NULL, 0); 1214 1215 /* 1216 * We need to progress in a 1217 * normal fork fashion 1218 */ 1219 goto normal_fork; 1220 } 1221 } 1222 1223 /* 1224 * Here the child has left home, 1225 * getting on with its life, so 1226 * so must we... 1227 */ 1228 forkparent(jp, cmd, mode, pid); 1229 goto parent; 1230 } 1231 VFORK_END 1232 } else { 1233 normal_fork:; 1234 #endif 1235 if (forkshell(jp, cmd, mode) != 0) 1236 goto parent; /* at end of routine */ 1237 CTRACE(DBG_PROCS|DBG_CMDS, ("Child sets EV_EXIT\n")); 1238 flags |= EV_EXIT; 1239 FORCEINTON; 1240 #ifdef DO_SHAREDVFORK 1241 } 1242 #endif 1243 if (flags & EV_BACKCMD) { 1244 if (!vforking) { 1245 FORCEINTON; 1246 } 1247 close(pip[0]); 1248 movefd(pip[1], 1); 1249 } 1250 flags |= EV_EXIT; 1251 } 1252 1253 /* 1254 * This is the child process if a fork occurred. 1255 * (or "the" process if there was no fork at all) 1256 * 1257 * Execute the command. 1258 */ 1259 1260 switch (cmdentry.cmdtype) { 1261 volatile int saved; 1262 struct funcdef * volatile savefunc; 1263 const char * volatile savectx; 1264 1265 case CMDFUNCTION: 1266 VXTRACE(DBG_EVAL, ("Shell function%s: ",vforking?" VF":""), 1267 trargs(argv)); 1268 redirect(cmd->ncmd.redirect, REDIR_KEEP | (saved = 1269 !(flags & EV_EXIT) || have_traps() ? REDIR_PUSH : 0)); 1270 saveparam = shellparam; 1271 shellparam.malloc = 0; 1272 shellparam.reset = 1; 1273 shellparam.nparam = argc - 1; 1274 shellparam.p = argv + 1; 1275 shellparam.optnext = NULL; 1276 INTOFF; 1277 savelocalvars = localvars; 1278 savectx = currentcontext; 1279 localvars = NULL; 1280 reffunc(savefunc = cmdentry.u.func); 1281 INTON; 1282 if (setjmp(jmploc.loc)) { 1283 if (exception == EXSHELLPROC) { 1284 freeparam((volatile struct shparam *) 1285 &saveparam); 1286 } else { 1287 freeparam(&shellparam); 1288 shellparam = saveparam; 1289 } 1290 if (saved) 1291 popredir(POPREDIR_UNDO); 1292 unreffunc(savefunc); 1293 poplocalvars(); 1294 localvars = savelocalvars; 1295 funclinebase = savefuncline; 1296 funclineabs = savefuncabs; 1297 currentcontext = savectx; 1298 handler = savehandler; 1299 longjmp(handler->loc, 1); 1300 } 1301 savehandler = handler; 1302 handler = &jmploc; 1303 if (cmdentry.u.func) { 1304 if (cmdentry.lno_frel) 1305 funclinebase = cmdentry.lineno - 1; 1306 else 1307 funclinebase = 0; 1308 funclineabs = cmdentry.lineno; 1309 currentcontext = argv[0]; 1310 1311 VTRACE(DBG_EVAL, 1312 ("function: node: %d '%s' # %d%s; funclinebase=%d\n", 1313 getfuncnode(cmdentry.u.func)->type, 1314 NODETYPENAME(getfuncnode(cmdentry.u.func)->type), 1315 cmdentry.lineno, cmdentry.lno_frel?" (=1)":"", 1316 funclinebase)); 1317 } 1318 listmklocal(varlist.list, VDOEXPORT | VEXPORT); 1319 /* stop shell blowing its stack */ 1320 if (++funcnest > 1000) 1321 error("too many nested function calls"); 1322 evaltree(getfuncnode(cmdentry.u.func), 1323 flags & (EV_TESTED|EV_EXIT)); 1324 funcnest--; 1325 INTOFF; 1326 unreffunc(cmdentry.u.func); 1327 poplocalvars(); 1328 localvars = savelocalvars; 1329 funclinebase = savefuncline; 1330 funclineabs = savefuncabs; 1331 currentcontext = savectx; 1332 freeparam(&shellparam); 1333 shellparam = saveparam; 1334 handler = savehandler; 1335 if (saved) 1336 popredir(POPREDIR_UNDO); 1337 INTON; 1338 if (evalskip == SKIPFUNC) { 1339 evalskip = SKIPNONE; 1340 skipcount = 0; 1341 } 1342 if (flags & EV_EXIT) 1343 exitshell(exitstatus); 1344 break; 1345 1346 case CMDSPLBLTIN: 1347 VTRACE(DBG_EVAL, ("special ")); 1348 case CMDBUILTIN: 1349 VXTRACE(DBG_EVAL, ("builtin command [%d]%s: ", argc, 1350 vforking ? " VF" : ""), trargs(argv)); 1351 1352 if (cmdentry.u.bltin == execcmd) { 1353 char **ap; 1354 1355 /* 1356 * Work out how we should process redirections 1357 * on the "exec" command. We need REDIR_KEEP 1358 * if we must not set close-on-exec, and REDIR_PUSH 1359 * if we need to be able to undo them (in the 1360 * exec command, only on some kind of error). 1361 * 1362 * Skip "exec" (argv[0]) then examine args. 1363 * 1364 * This must be done manually, as nextopt() 1365 * hasn't been init'd for this command yet. 1366 * And it won't be until after redirections are done. 1367 * 1368 * "exec" currently takes no options (except "--"), 1369 * but might one day, and this needs to keep working, 1370 * so do it, kind of, properly. 1371 * 1372 * Note in the common cases argv[1] will be NULL 1373 * (for exec just setting up redirectons) or will 1374 * not start with a '-' ("exec cmd") so normally 1375 * this loop will either never start or will break 1376 * at the first test of the first iteration. 1377 */ 1378 for (ap = argv + 1; *ap != NULL; ap++) { 1379 1380 if (ap[0][0] != '-') 1381 break; 1382 1383 if (ap[0][1] == '\0') /* "exec -" */ 1384 break; /* or continue ?? */ 1385 1386 if (ap[0][1] == '-' && ap[0][2] == '\0') { 1387 ap++; 1388 break; 1389 } 1390 1391 #if defined(DUMMY_EXAMPLE_CODE) && 0 1392 /* 1393 * if options are added to "exec" then 1394 * any which take an arg (like the common 1395 * in other shells "-a cmdname") need to 1396 * be recognised here, lest "cmdname" be 1397 * thought to be the cmd to exec 1398 */ 1399 1400 for (char *op = ap[0] + 1; *op; op++) { 1401 switch (*op) { 1402 case 'a': 1403 case any others similar: 1404 /* options needing an optarg */ 1405 if (op[1] == '\0' && ap[1]) 1406 ap++; 1407 break; 1408 1409 default: 1410 /* options with no optarg */ 1411 continue; 1412 } 1413 break; 1414 } 1415 #endif /* DUMMY EXAMPLE CODE */ 1416 } 1417 1418 if (*ap != NULL) 1419 mode = REDIR_KEEP; /* exec cmd <... */ 1420 else 1421 mode = 0; /* exec < .... */ 1422 1423 /* 1424 * always save old fd setup in case of error() 1425 * execcmd() will undo this if no error occurs 1426 * (that is, in the case the shell has not vanished) 1427 */ 1428 mode |= REDIR_PUSH; 1429 } else /* any builtin execpt "exec" */ 1430 mode = REDIR_PUSH | REDIR_KEEP; 1431 1432 if (flags == EV_BACKCMD) { 1433 memout.nleft = 0; 1434 memout.nextc = memout.buf; 1435 memout.bufsize = 64; 1436 mode |= REDIR_BACKQ; 1437 } 1438 1439 e = -1; 1440 savecmdname = commandname; 1441 savetopfile = getcurrentfile(); 1442 savehandler = handler; 1443 temp_path = 0; 1444 1445 if (!setjmp(jmploc.loc)) { 1446 handler = &jmploc; 1447 1448 /* 1449 * We need to ensure the command hash table isn't 1450 * corrupted by temporary PATH assignments. 1451 * However we must ensure the 'local' command works! 1452 */ 1453 if (path != pathval() && (cmdentry.u.bltin == hashcmd || 1454 cmdentry.u.bltin == typecmd)) { 1455 savelocalvars = localvars; 1456 localvars = 0; 1457 temp_path = 1; 1458 mklocal(path - 5 /* PATH= */, 0); 1459 } 1460 redirect(cmd->ncmd.redirect, mode); 1461 1462 /* 1463 * the empty command is regarded as a normal 1464 * builtin for the purposes of redirects, but 1465 * is a special builtin for var assigns. 1466 * (unless we are the "command" command.) 1467 */ 1468 if (argc == 0 && !(cmd_flags & DO_NOFUNC)) 1469 cmdentry.cmdtype = CMDSPLBLTIN; 1470 1471 /* exec is a special builtin, but needs this list... */ 1472 cmdenviron = varlist.list; 1473 /* we must check 'readonly' flag for all builtins */ 1474 listsetvar(varlist.list, 1475 cmdentry.cmdtype == CMDSPLBLTIN ? 0 : VNOSET); 1476 commandname = argv[0]; 1477 /* initialize nextopt */ 1478 argptr = argv + 1; 1479 optptr = NULL; 1480 /* and getopt */ 1481 optreset = 1; 1482 optind = 1; 1483 builtin_flags = flags; 1484 clr_err(out1); /* discard previous I/O errors */ 1485 exitstatus = cmdentry.u.bltin(argc, argv); 1486 } else { 1487 e = exception; 1488 if (e == EXINT) 1489 exitstatus = SIGINT + 128; 1490 else if (e == EXEXEC) 1491 exitstatus = exerrno; 1492 else if (e != EXEXIT) 1493 exitstatus = 2; 1494 } 1495 handler = savehandler; 1496 flushall(); 1497 out1 = &output; 1498 out2 = &errout; 1499 freestdout(); 1500 if (temp_path) { 1501 poplocalvars(); 1502 localvars = savelocalvars; 1503 } 1504 cmdenviron = NULL; 1505 if (e != EXSHELLPROC) { 1506 commandname = savecmdname; 1507 if (flags & EV_EXIT) 1508 exitshell(exitstatus); 1509 } 1510 if (e != -1) { 1511 if ((e != EXERROR && e != EXEXEC) 1512 || cmdentry.cmdtype == CMDSPLBLTIN) 1513 exraise(e); 1514 popfilesupto(savetopfile); 1515 FORCEINTON; 1516 } 1517 1518 if (cmdentry.u.bltin != execcmd) 1519 popredir(POPREDIR_UNDO); 1520 1521 if (flags == EV_BACKCMD) { 1522 backcmd->buf = memout.buf; 1523 backcmd->nleft = memout.nextc - memout.buf; 1524 memout.buf = NULL; 1525 } 1526 break; 1527 1528 default: 1529 VXTRACE(DBG_EVAL, ("normal command%s: ", vforking?" VF":""), 1530 trargs(argv)); 1531 redirect(cmd->ncmd.redirect, 1532 (vforking ? REDIR_VFORK : 0) | REDIR_KEEP); 1533 if (!vforking) 1534 for (sp = varlist.list ; sp ; sp = sp->next) 1535 setvareq(sp->text, VDOEXPORT|VEXPORT|VSTACK); 1536 envp = environment(); 1537 shellexec(argv, envp, path, cmdentry.u.index, vforking); 1538 break; 1539 } 1540 goto out; 1541 1542 parent:; /* parent process gets here (if we forked) */ 1543 1544 exitstatus = 0; /* if not altered just below */ 1545 if (mode == FORK_FG) { /* argument to fork */ 1546 exitstatus = waitforjob(jp); 1547 } else if (mode == FORK_NOJOB) { 1548 backcmd->fd = pip[0]; 1549 close(pip[1]); 1550 backcmd->jp = jp; 1551 } else 1552 jobstarted(jp); 1553 1554 FORCEINTON; 1555 1556 out:; 1557 if (lastarg) 1558 /* implement $_ for whatever use that really is */ 1559 (void) setvarsafe("_", lastarg, VNOERROR); 1560 popstackmark(&smark); 1561 } 1562 1563 1564 /* 1565 * Search for a command. This is called before we fork so that the 1566 * location of the command will be available in the parent as well as 1567 * the child. The check for "goodname" is an overly conservative 1568 * check that the name will not be subject to expansion. 1569 */ 1570 1571 STATIC void 1572 prehash(union node *n) 1573 { 1574 struct cmdentry entry; 1575 1576 if (n && n->type == NCMD && n->ncmd.args) 1577 if (goodname(n->ncmd.args->narg.text)) 1578 find_command(n->ncmd.args->narg.text, &entry, 0, 1579 pathval()); 1580 } 1581 1582 int 1583 in_function(void) 1584 { 1585 return funcnest; 1586 } 1587 1588 enum skipstate 1589 current_skipstate(void) 1590 { 1591 return evalskip; 1592 } 1593 1594 void 1595 save_skipstate(struct skipsave *p) 1596 { 1597 *p = s_k_i_p; 1598 } 1599 1600 void 1601 restore_skipstate(const struct skipsave *p) 1602 { 1603 s_k_i_p = *p; 1604 } 1605 1606 void 1607 stop_skipping(void) 1608 { 1609 evalskip = SKIPNONE; 1610 skipcount = 0; 1611 } 1612 1613 /* 1614 * Builtin commands. Builtin commands whose functions are closely 1615 * tied to evaluation are implemented here. 1616 */ 1617 1618 /* 1619 * No command given. 1620 */ 1621 1622 int 1623 bltincmd(int argc, char **argv) 1624 { 1625 /* 1626 * Preserve exitstatus of a previous possible redirection 1627 * as POSIX mandates 1628 */ 1629 return back_exitstatus; 1630 } 1631 1632 1633 /* 1634 * Handle break and continue commands. Break, continue, and return are 1635 * all handled by setting the evalskip flag. The evaluation routines 1636 * above all check this flag, and if it is set they start skipping 1637 * commands rather than executing them. The variable skipcount is 1638 * the number of loops to break/continue, or the number of function 1639 * levels to return. (The latter is always 1.) It should probably 1640 * be an error to break out of more loops than exist, but it isn't 1641 * in the standard shell so we don't make it one here. 1642 */ 1643 1644 int 1645 breakcmd(int argc, char **argv) 1646 { 1647 int n = argc > 1 ? number(argv[1]) : 1; 1648 1649 if (n <= 0) 1650 error("invalid count: %d", n); 1651 if (n > loopnest) 1652 n = loopnest; 1653 if (n > 0) { 1654 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK; 1655 skipcount = n; 1656 } 1657 return 0; 1658 } 1659 1660 int 1661 dotcmd(int argc, char **argv) 1662 { 1663 exitstatus = 0; 1664 1665 (void) nextopt(NULL); /* ignore a leading "--" */ 1666 1667 if (*argptr != NULL) { /* That's what SVR2 does */ 1668 char *fullname; 1669 /* 1670 * dot_funcnest needs to be 0 when not in a dotcmd, so it 1671 * cannot be restored with (funcnest + 1). 1672 */ 1673 int dot_funcnest_old; 1674 struct stackmark smark; 1675 1676 setstackmark(&smark); 1677 fullname = find_dot_file(*argptr); 1678 setinputfile(fullname, 1); 1679 commandname = fullname; 1680 dot_funcnest_old = dot_funcnest; 1681 dot_funcnest = funcnest + 1; 1682 cmdloop(0); 1683 dot_funcnest = dot_funcnest_old; 1684 popfile(); 1685 popstackmark(&smark); 1686 } 1687 return exitstatus; 1688 } 1689 1690 /* 1691 * allow dotfile function nesting to be manipulated 1692 * (for read_profile). This allows profile files to 1693 * be treated as if they were used as '.' commands, 1694 * (approximately) and in particular, for "return" to work. 1695 */ 1696 int 1697 set_dot_funcnest(int new) 1698 { 1699 int rv = dot_funcnest; 1700 1701 if (new >= 0) 1702 dot_funcnest = new; 1703 1704 return rv; 1705 } 1706 1707 /* 1708 * Take commands from a file. To be compatible we should do a path 1709 * search for the file, which is necessary to find sub-commands. 1710 */ 1711 1712 STATIC char * 1713 find_dot_file(char *basename) 1714 { 1715 char *fullname; 1716 const char *path = pathval(); 1717 struct stat statb; 1718 1719 /* don't try this for absolute or relative paths */ 1720 if (strchr(basename, '/')) { 1721 if (stat(basename, &statb) == 0) { 1722 if (S_ISDIR(statb.st_mode)) 1723 error("%s: is a directory", basename); 1724 if (S_ISBLK(statb.st_mode)) 1725 error("%s: is a block device", basename); 1726 return basename; 1727 } 1728 } else while ((fullname = padvance(&path, basename, 1)) != NULL) { 1729 if ((stat(fullname, &statb) == 0)) { 1730 /* weird format is to ease future code... */ 1731 if (S_ISDIR(statb.st_mode) || S_ISBLK(statb.st_mode)) 1732 ; 1733 #if notyet 1734 else if (unreadable()) { 1735 /* 1736 * testing this via st_mode is ugly to get 1737 * correct (and would ignore ACLs). 1738 * better way is just to open the file. 1739 * But doing that here would (currently) 1740 * mean opening the file twice, which 1741 * might not be safe. So, defer this 1742 * test until code is restructured so 1743 * we can return a fd. Then we also 1744 * get to fix the mem leak just below... 1745 */ 1746 } 1747 #endif 1748 else { 1749 /* 1750 * Don't bother freeing here, since 1751 * it will be freed by the caller. 1752 * XXX no it won't - a bug for later. 1753 */ 1754 return fullname; 1755 } 1756 } 1757 stunalloc(fullname); 1758 } 1759 1760 /* not found in the PATH */ 1761 error("%s: not found", basename); 1762 /* NOTREACHED */ 1763 } 1764 1765 1766 1767 /* 1768 * The return command. 1769 * 1770 * Quoth the POSIX standard: 1771 * The return utility shall cause the shell to stop executing the current 1772 * function or dot script. If the shell is not currently executing 1773 * a function or dot script, the results are unspecified. 1774 * 1775 * As for the unspecified part, there seems to be no de-facto standard: bash 1776 * ignores the return with a warning, zsh ignores the return in interactive 1777 * mode but seems to liken it to exit in a script. (checked May 2014) 1778 * 1779 * We choose to silently ignore the return. Older versions of this shell 1780 * set evalskip to SKIPFILE causing the shell to (indirectly) exit. This 1781 * had at least the problem of circumventing the check for stopped jobs, 1782 * which would occur for exit or ^D. 1783 */ 1784 1785 int 1786 returncmd(int argc, char **argv) 1787 { 1788 int ret = argc > 1 ? number(argv[1]) : exitstatus; 1789 1790 if ((dot_funcnest == 0 && funcnest) 1791 || (dot_funcnest > 0 && funcnest - (dot_funcnest - 1) > 0)) { 1792 evalskip = SKIPFUNC; 1793 skipcount = 1; 1794 } else if (dot_funcnest > 0) { 1795 evalskip = SKIPFILE; 1796 skipcount = 1; 1797 } else { 1798 /* XXX: should a warning be issued? */ 1799 ret = 0; 1800 } 1801 1802 return ret; 1803 } 1804 1805 1806 int 1807 falsecmd(int argc, char **argv) 1808 { 1809 return 1; 1810 } 1811 1812 1813 int 1814 truecmd(int argc, char **argv) 1815 { 1816 return 0; 1817 } 1818 1819 1820 int 1821 execcmd(int argc, char **argv) 1822 { 1823 /* 1824 * BEWARE: if any options are added here, they must 1825 * also be added in evalcommand(), look for "DUMMY_EXAMPLE_CODE" 1826 * for example code for there. Here the options would be 1827 * processed completely normally. 1828 */ 1829 (void) nextopt(""); /* ignore a leading "--" */ 1830 1831 if (*argptr) { 1832 struct strlist *sp; 1833 1834 iflag = 0; /* exit on error */ 1835 mflag = 0; 1836 optschanged(); 1837 for (sp = cmdenviron; sp; sp = sp->next) 1838 setvareq(sp->text, VDOEXPORT|VEXPORT|VSTACK); 1839 shellexec(argptr, environment(), pathval(), 0, 0); 1840 /* NOTREACHED */ 1841 } 1842 popredir(POPREDIR_PERMANENT); /* make any redirections permanent */ 1843 return 0; 1844 } 1845 1846 static int 1847 conv_time(clock_t ticks, char *seconds, size_t l) 1848 { 1849 static clock_t tpm = 0; 1850 clock_t mins; 1851 int i; 1852 1853 if (!tpm) 1854 tpm = sysconf(_SC_CLK_TCK) * 60; 1855 1856 mins = ticks / tpm; 1857 snprintf(seconds, l, "%.4f", (ticks - mins * tpm) * 60.0 / tpm ); 1858 1859 if (seconds[0] == '6' && seconds[1] == '0') { 1860 /* 59.99995 got rounded up... */ 1861 mins++; 1862 strlcpy(seconds, "0.0", l); 1863 return mins; 1864 } 1865 1866 /* suppress trailing zeros */ 1867 i = strlen(seconds) - 1; 1868 for (; seconds[i] == '0' && seconds[i - 1] != '.'; i--) 1869 seconds[i] = 0; 1870 return mins; 1871 } 1872 1873 int 1874 timescmd(int argc, char **argv) 1875 { 1876 struct tms tms; 1877 int u, s, cu, cs; 1878 char us[8], ss[8], cus[8], css[8]; 1879 1880 nextopt(""); 1881 1882 times(&tms); 1883 1884 u = conv_time(tms.tms_utime, us, sizeof(us)); 1885 s = conv_time(tms.tms_stime, ss, sizeof(ss)); 1886 cu = conv_time(tms.tms_cutime, cus, sizeof(cus)); 1887 cs = conv_time(tms.tms_cstime, css, sizeof(css)); 1888 1889 outfmt(out1, "%dm%ss %dm%ss\n%dm%ss %dm%ss\n", 1890 u, us, s, ss, cu, cus, cs, css); 1891 1892 return 0; 1893 } 1894