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