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