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