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