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