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