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