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