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