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