source: trunk/src/kash/eval.c@ 2653

Last change on this file since 2653 was 2653, checked in by bird, 13 years ago

kash: fixed shfile_opendir on windows, and thereby argument expansion.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 29.4 KB
Line 
1/* $NetBSD: eval.c,v 1.84 2005/06/23 23:05:29 christos 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#if 0
36#ifndef lint
37static char sccsid[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95";
38#else
39__RCSID("$NetBSD: eval.c,v 1.84 2005/06/23 23:05:29 christos Exp $");
40#endif /* not lint */
41#endif
42
43#include <stdlib.h>
44#include <stdio.h>
45#include <sys/types.h>
46#ifdef HAVE_SYSCTL_H
47# ifdef __OpenBSD__ /* joyful crap */
48# include <sys/param.h>
49# undef psh
50# endif
51# include <sys/sysctl.h>
52#endif
53
54/*
55 * Evaluate a command.
56 */
57
58#include "shell.h"
59#include "nodes.h"
60#include "syntax.h"
61#include "expand.h"
62#include "parser.h"
63#include "jobs.h"
64#include "eval.h"
65#include "builtins.h"
66#include "options.h"
67#include "exec.h"
68#include "redir.h"
69#include "input.h"
70#include "output.h"
71#include "trap.h"
72#include "var.h"
73#include "memalloc.h"
74#include "error.h"
75#include "show.h"
76#include "mystring.h"
77#include "main.h"
78#ifndef SMALL
79# include "myhistedit.h"
80#endif
81#include "shinstance.h"
82
83
84/* flags in argument to evaltree */
85#define EV_EXIT 01 /* exit after evaluating tree */
86#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
87#define EV_BACKCMD 04 /* command executing within back quotes */
88
89/*int evalskip;*/ /* set if we are skipping commands */
90/*STATIC int skipcount;*/ /* number of levels to skip */
91/*MKINIT int loopnest;*/ /* current loop nesting level */
92/*int funcnest;*/ /* depth of function calls */
93
94
95/*char *commandname;*/
96/*struct strlist *cmdenviron;*/
97/*int exitstatus;*/ /* exit status of last command */
98/*int back_exitstatus;*/ /* exit status of backquoted command */
99
100
101STATIC void evalloop(shinstance *, union node *, int);
102STATIC void evalfor(shinstance *, union node *, int);
103STATIC void evalcase(shinstance *, union node *, int);
104STATIC void evalsubshell(shinstance *, union node *, int);
105STATIC void expredir(shinstance *, union node *);
106STATIC void evalpipe(shinstance *, union node *);
107STATIC void evalcommand(shinstance *, union node *, int, struct backcmd *);
108STATIC void prehash(shinstance *, union node *);
109
110
111/*
112 * Called to reset things after an exception.
113 */
114
115#ifdef mkinit
116INCLUDE "eval.h"
117
118RESET {
119 psh->evalskip = 0;
120 psh->loopnest = 0;
121 psh->funcnest = 0;
122}
123
124SHELLPROC {
125 psh->exitstatus = 0;
126}
127#endif
128
129static int
130sh_pipe(shinstance *psh, int fds[2])
131{
132 int nfd;
133
134 if (shfile_pipe(&psh->fdtab, fds))
135 return -1;
136
137 if (fds[0] < 3) {
138 nfd = shfile_fcntl(&psh->fdtab, fds[0], F_DUPFD, 3);
139 if (nfd != -1) {
140 shfile_close(&psh->fdtab, fds[0]);
141 fds[0] = nfd;
142 }
143 }
144
145 if (fds[1] < 3) {
146 nfd = shfile_fcntl(&psh->fdtab, fds[1], F_DUPFD, 3);
147 if (nfd != -1) {
148 shfile_close(&psh->fdtab, fds[1]);
149 fds[1] = nfd;
150 }
151 }
152 return 0;
153}
154
155
156/*
157 * The eval commmand.
158 */
159
160int
161evalcmd(shinstance *psh, int argc, char **argv)
162{
163 char *p;
164 char *concat;
165 char **ap;
166
167 if (argc > 1) {
168 p = argv[1];
169 if (argc > 2) {
170 STARTSTACKSTR(psh, concat);
171 ap = argv + 2;
172 for (;;) {
173 while (*p)
174 STPUTC(psh, *p++, concat);
175 if ((p = *ap++) == NULL)
176 break;
177 STPUTC(psh, ' ', concat);
178 }
179 STPUTC(psh, '\0', concat);
180 p = grabstackstr(psh, concat);
181 }
182 evalstring(psh, p, EV_TESTED);
183 }
184 return psh->exitstatus;
185}
186
187
188/*
189 * Execute a command or commands contained in a string.
190 */
191
192void
193evalstring(shinstance *psh, char *s, int flag)
194{
195 union node *n;
196 struct stackmark smark;
197
198 setstackmark(psh, &smark);
199 setinputstring(psh, s, 1);
200
201 while ((n = parsecmd(psh, 0)) != NEOF) {
202 evaltree(psh, n, flag);
203 popstackmark(psh, &smark);
204 }
205 popfile(psh);
206 popstackmark(psh, &smark);
207}
208
209
210
211/*
212 * Evaluate a parse tree. The value is left in the global variable
213 * exitstatus.
214 */
215
216void
217evaltree(shinstance *psh, union node *n, int flags)
218{
219 if (n == NULL) {
220 TRACE((psh, "evaltree(NULL) called\n"));
221 psh->exitstatus = 0;
222 goto out;
223 }
224#ifndef SMALL
225 psh->displayhist = 1; /* show history substitutions done with fc */
226#endif
227 TRACE((psh, "pid %d, evaltree(%p: %d, %d) called\n",
228 sh_getpid(psh), n, n->type, flags));
229 switch (n->type) {
230 case NSEMI:
231 evaltree(psh, n->nbinary.ch1, flags & EV_TESTED);
232 if (psh->evalskip)
233 goto out;
234 evaltree(psh, n->nbinary.ch2, flags);
235 break;
236 case NAND:
237 evaltree(psh, n->nbinary.ch1, EV_TESTED);
238 if (psh->evalskip || psh->exitstatus != 0)
239 goto out;
240 evaltree(psh, n->nbinary.ch2, flags);
241 break;
242 case NOR:
243 evaltree(psh, n->nbinary.ch1, EV_TESTED);
244 if (psh->evalskip || psh->exitstatus == 0)
245 goto out;
246 evaltree(psh, n->nbinary.ch2, flags);
247 break;
248 case NREDIR:
249 expredir(psh, n->nredir.redirect);
250 redirect(psh, n->nredir.redirect, REDIR_PUSH);
251 evaltree(psh, n->nredir.n, flags);
252 popredir(psh);
253 break;
254 case NSUBSHELL:
255 evalsubshell(psh, n, flags);
256 break;
257 case NBACKGND:
258 evalsubshell(psh, n, flags);
259 break;
260 case NIF: {
261 evaltree(psh, n->nif.test, EV_TESTED);
262 if (psh->evalskip)
263 goto out;
264 if (psh->exitstatus == 0)
265 evaltree(psh, n->nif.ifpart, flags);
266 else if (n->nif.elsepart)
267 evaltree(psh, n->nif.elsepart, flags);
268 else
269 psh->exitstatus = 0;
270 break;
271 }
272 case NWHILE:
273 case NUNTIL:
274 evalloop(psh, n, flags);
275 break;
276 case NFOR:
277 evalfor(psh, n, flags);
278 break;
279 case NCASE:
280 evalcase(psh, n, flags);
281 break;
282 case NDEFUN:
283 defun(psh, n->narg.text, n->narg.next);
284 psh->exitstatus = 0;
285 break;
286 case NNOT:
287 evaltree(psh, n->nnot.com, EV_TESTED);
288 psh->exitstatus = !psh->exitstatus;
289 break;
290 case NPIPE:
291 evalpipe(psh, n);
292 break;
293 case NCMD:
294 evalcommand(psh, n, flags, (struct backcmd *)NULL);
295 break;
296 default:
297 out1fmt(psh, "Node type = %d\n", n->type);
298 flushout(&psh->output);
299 break;
300 }
301out:
302 if (psh->pendingsigs)
303 dotrap(psh);
304 if ((flags & EV_EXIT) != 0)
305 exitshell(psh, psh->exitstatus);
306}
307
308
309STATIC void
310evalloop(shinstance *psh, union node *n, int flags)
311{
312 int status;
313
314 psh->loopnest++;
315 status = 0;
316 for (;;) {
317 evaltree(psh, n->nbinary.ch1, EV_TESTED);
318 if (psh->evalskip) {
319skipping: if (psh->evalskip == SKIPCONT && --psh->skipcount <= 0) {
320 psh->evalskip = 0;
321 continue;
322 }
323 if (psh->evalskip == SKIPBREAK && --psh->skipcount <= 0)
324 psh->evalskip = 0;
325 break;
326 }
327 if (n->type == NWHILE) {
328 if (psh->exitstatus != 0)
329 break;
330 } else {
331 if (psh->exitstatus == 0)
332 break;
333 }
334 evaltree(psh, n->nbinary.ch2, flags & EV_TESTED);
335 status = psh->exitstatus;
336 if (psh->evalskip)
337 goto skipping;
338 }
339 psh->loopnest--;
340 psh->exitstatus = status;
341}
342
343
344
345STATIC void
346evalfor(shinstance *psh, union node *n, int flags)
347{
348 struct arglist arglist;
349 union node *argp;
350 struct strlist *sp;
351 struct stackmark smark;
352 int status = 0;
353
354 setstackmark(psh, &smark);
355 arglist.lastp = &arglist.list;
356 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
357 expandarg(psh, argp, &arglist, EXP_FULL | EXP_TILDE);
358 if (psh->evalskip)
359 goto out;
360 }
361 *arglist.lastp = NULL;
362
363 psh->loopnest++;
364 for (sp = arglist.list ; sp ; sp = sp->next) {
365 setvar(psh, n->nfor.var, sp->text, 0);
366 evaltree(psh, n->nfor.body, flags & EV_TESTED);
367 status = psh->exitstatus;
368 if (psh->evalskip) {
369 if (psh->evalskip == SKIPCONT && --psh->skipcount <= 0) {
370 psh->evalskip = 0;
371 continue;
372 }
373 if (psh->evalskip == SKIPBREAK && --psh->skipcount <= 0)
374 psh->evalskip = 0;
375 break;
376 }
377 }
378 psh->loopnest--;
379 psh->exitstatus = status;
380out:
381 popstackmark(psh, &smark);
382}
383
384
385
386STATIC void
387evalcase(shinstance *psh, union node *n, int flags)
388{
389 union node *cp;
390 union node *patp;
391 struct arglist arglist;
392 struct stackmark smark;
393 int status = 0;
394
395 setstackmark(psh, &smark);
396 arglist.lastp = &arglist.list;
397 expandarg(psh, n->ncase.expr, &arglist, EXP_TILDE);
398 for (cp = n->ncase.cases ; cp && psh->evalskip == 0 ; cp = cp->nclist.next) {
399 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
400 if (casematch(psh, patp, arglist.list->text)) {
401 if (psh->evalskip == 0) {
402 evaltree(psh, cp->nclist.body, flags);
403 status = psh->exitstatus;
404 }
405 goto out;
406 }
407 }
408 }
409out:
410 psh->exitstatus = status;
411 popstackmark(psh, &smark);
412}
413
414
415
416/*
417 * Kick off a subshell to evaluate a tree.
418 */
419
420STATIC void
421evalsubshell(shinstance *psh, union node *n, int flags)
422{
423 struct job *jp;
424 int backgnd = (n->type == NBACKGND);
425
426 expredir(psh, n->nredir.redirect);
427 INTOFF;
428 jp = makejob(psh, n, 1);
429 if (forkshell(psh, jp, n, backgnd ? FORK_BG : FORK_FG) == 0) {
430 INTON;
431 if (backgnd)
432 flags &=~ EV_TESTED;
433 redirect(psh, n->nredir.redirect, 0);
434 /* never returns */
435 evaltree(psh, n->nredir.n, flags | EV_EXIT);
436 }
437 if (! backgnd)
438 psh->exitstatus = waitforjob(psh, jp);
439 INTON;
440}
441
442
443
444/*
445 * Compute the names of the files in a redirection list.
446 */
447
448STATIC void
449expredir(shinstance *psh, union node *n)
450{
451 union node *redir;
452
453 for (redir = n ; redir ; redir = redir->nfile.next) {
454 struct arglist fn;
455 fn.lastp = &fn.list;
456 switch (redir->type) {
457 case NFROMTO:
458 case NFROM:
459 case NTO:
460 case NCLOBBER:
461 case NAPPEND:
462 expandarg(psh, redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
463 redir->nfile.expfname = fn.list->text;
464 break;
465 case NFROMFD:
466 case NTOFD:
467 if (redir->ndup.vname) {
468 expandarg(psh, redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
469 fixredir(psh, redir, fn.list->text, 1);
470 }
471 break;
472 }
473 }
474}
475
476
477
478/*
479 * Evaluate a pipeline. All the processes in the pipeline are children
480 * of the process creating the pipeline. (This differs from some versions
481 * of the shell, which make the last process in a pipeline the parent
482 * of all the rest.)
483 */
484
485STATIC void
486evalpipe(shinstance *psh, union node *n)
487{
488 struct job *jp;
489 struct nodelist *lp;
490 int pipelen;
491 int prevfd;
492 int pip[2];
493
494 TRACE((psh, "evalpipe(0x%lx) called\n", (long)n));
495 pipelen = 0;
496 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
497 pipelen++;
498 INTOFF;
499 jp = makejob(psh, n, pipelen);
500 prevfd = -1;
501 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
502 prehash(psh, lp->n);
503 pip[1] = -1;
504 if (lp->next) {
505 if (sh_pipe(psh, pip) < 0) {
506 shfile_close(&psh->fdtab, prevfd);
507 error(psh, "Pipe call failed");
508 }
509 }
510 if (forkshell(psh, jp, lp->n, n->npipe.backgnd ? FORK_BG : FORK_FG) == 0) {
511 INTON;
512 if (prevfd > 0) {
513 movefd(psh, prevfd, 0);
514 }
515 if (pip[1] >= 0) {
516 shfile_close(&psh->fdtab, pip[0]);
517 if (pip[1] != 1) {
518 movefd(psh, pip[1], 1);
519 }
520 }
521 evaltree(psh, lp->n, EV_EXIT);
522 }
523 if (prevfd >= 0)
524 shfile_close(&psh->fdtab, prevfd);
525 prevfd = pip[0];
526 shfile_close(&psh->fdtab, pip[1]);
527 }
528 if (n->npipe.backgnd == 0) {
529 psh->exitstatus = waitforjob(psh, jp);
530 TRACE((psh, "evalpipe: job done exit status %d\n", psh->exitstatus));
531 }
532 INTON;
533}
534
535
536
537/*
538 * Execute a command inside back quotes. If it's a builtin command, we
539 * want to save its output in a block obtained from malloc. Otherwise
540 * we fork off a subprocess and get the output of the command via a pipe.
541 * Should be called with interrupts off.
542 */
543
544void
545evalbackcmd(shinstance *psh, union node *n, struct backcmd *result)
546{
547 int pip[2];
548 struct job *jp;
549 struct stackmark smark; /* unnecessary */
550
551 setstackmark(psh, &smark);
552 result->fd = -1;
553 result->buf = NULL;
554 result->nleft = 0;
555 result->jp = NULL;
556 if (n == NULL) {
557 goto out;
558 }
559#ifdef notyet
560 /*
561 * For now we disable executing builtins in the same
562 * context as the shell, because we are not keeping
563 * enough state to recover from changes that are
564 * supposed only to affect subshells. eg. echo "`cd /`"
565 */
566 if (n->type == NCMD) {
567 psh->exitstatus = opsh->exitstatus;
568 evalcommand(psh, n, EV_BACKCMD, result);
569 } else
570#endif
571 {
572 INTOFF;
573 if (sh_pipe(psh, pip) < 0)
574 error(psh, "Pipe call failed");
575 jp = makejob(psh, n, 1);
576 if (forkshell(psh, jp, n, FORK_NOJOB) == 0) {
577 FORCEINTON;
578 shfile_close(&psh->fdtab, pip[0]);
579 if (pip[1] != 1) {
580 movefd(psh, pip[1], 1);
581 }
582 eflag(psh) = 0;
583 evaltree(psh, n, EV_EXIT);
584 /* NOTREACHED */
585 }
586 shfile_close(&psh->fdtab, pip[1]);
587 result->fd = pip[0];
588 result->jp = jp;
589 INTON;
590 }
591out:
592 popstackmark(psh, &smark);
593 TRACE((psh, "evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
594 result->fd, result->buf, result->nleft, result->jp));
595}
596
597static const char *
598syspath(shinstance *psh)
599{
600#ifdef CTL_USER
601 static char *sys_path = NULL;
602 static int mib[] = {CTL_USER, USER_CS_PATH};
603#endif
604#ifdef PC_PATH_SEP
605 static char def_path[] = "PATH=/usr/bin;/bin;/usr/sbin;/sbin";
606#else
607 static char def_path[] = "PATH=/usr/bin:/bin:/usr/sbin:/sbin";
608#endif
609#ifdef CTL_USER
610 size_t len;
611
612 if (sys_path == NULL) {
613 if (sysctl(mib, 2, 0, &len, 0, 0) != -1 &&
614 (sys_path = ckmalloc(psh, len + 5)) != NULL &&
615 sysctl(mib, 2, sys_path + 5, &len, 0, 0) != -1) {
616 memcpy(sys_path, "PATH=", 5);
617 } else {
618 ckfree(psh, sys_path);
619 /* something to keep things happy */
620 sys_path = def_path;
621 }
622 }
623 return sys_path;
624#else
625 return def_path;
626#endif
627}
628
629static int
630parse_command_args(shinstance *psh, int argc, char **argv, int *use_syspath)
631{
632 int sv_argc = argc;
633 char *cp, c;
634
635 *use_syspath = 0;
636
637 for (;;) {
638 argv++;
639 if (--argc == 0)
640 break;
641 cp = *argv;
642 if (*cp++ != '-')
643 break;
644 if (*cp == '-' && cp[1] == 0) {
645 argv++;
646 argc--;
647 break;
648 }
649 while ((c = *cp++)) {
650 switch (c) {
651 case 'p':
652 *use_syspath = 1;
653 break;
654 default:
655 /* run 'typecmd' for other options */
656 return 0;
657 }
658 }
659 }
660 return sv_argc - argc;
661}
662
663/*int vforked = 0;*/
664
665/*
666 * Execute a simple command.
667 */
668
669STATIC void
670evalcommand(shinstance *psh, union node *cmd, int flags, struct backcmd *backcmd)
671{
672 struct stackmark smark;
673 union node *argp;
674 struct arglist arglist;
675 struct arglist varlist;
676 char **argv;
677 int argc;
678 char **envp;
679 int varflag;
680 struct strlist *sp;
681 int mode;
682 int pip[2];
683 struct cmdentry cmdentry;
684 struct job *jp;
685 struct jmploc jmploc;
686 struct jmploc *volatile savehandler;
687 char *volatile savecmdname;
688 volatile struct shparam saveparam;
689 struct localvar *volatile savelocalvars;
690 volatile int e;
691 char *lastarg;
692 const char *path = pathval(psh);
693 volatile int temp_path;
694#if __GNUC__
695 /* Avoid longjmp clobbering */
696 (void) &argv;
697 (void) &argc;
698 (void) &lastarg;
699 (void) &flags;
700#endif
701
702 psh->vforked = 0;
703 /* First expand the arguments. */
704 TRACE((psh, "evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
705 setstackmark(psh, &smark);
706 psh->back_exitstatus = 0;
707
708 /** @todo r=bird: Why is arguments and envvars expanded in this
709 * particular order? It would be both faster and simpler to do the
710 * envvars first and then continue with the arguments... */
711 arglist.lastp = &arglist.list;
712 varflag = 1;
713 /* Expand arguments, ignoring the initial 'name=value' ones */
714 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
715 char *p = argp->narg.text;
716 if (varflag && is_name(*p)) {
717 do {
718 p++;
719 } while (is_in_name(*p));
720 if (*p == '=')
721 continue;
722 }
723 expandarg(psh, argp, &arglist, EXP_FULL | EXP_TILDE);
724 varflag = 0;
725 }
726 *arglist.lastp = NULL;
727
728 expredir(psh, cmd->ncmd.redirect);
729
730 /* Now do the initial 'name=value' ones we skipped above */
731 varlist.lastp = &varlist.list;
732 for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
733 char *p = argp->narg.text;
734 if (!is_name(*p))
735 break;
736 do
737 p++;
738 while (is_in_name(*p));
739 if (*p != '=')
740 break;
741 expandarg(psh, argp, &varlist, EXP_VARTILDE);
742 }
743 *varlist.lastp = NULL;
744
745 argc = 0;
746 for (sp = arglist.list ; sp ; sp = sp->next)
747 argc++;
748 argv = stalloc(psh, sizeof (char *) * (argc + 1));
749
750 for (sp = arglist.list ; sp ; sp = sp->next) {
751 TRACE((psh, "evalcommand arg: %s\n", sp->text));
752 *argv++ = sp->text;
753 }
754 *argv = NULL;
755 lastarg = NULL;
756 if (iflag(psh) && psh->funcnest == 0 && argc > 0)
757 lastarg = argv[-1];
758 argv -= argc;
759
760 /* Print the command if xflag is set. */
761 if (xflag(psh)) {
762 char sep = 0;
763 out2str(psh, ps4val(psh));
764 for (sp = varlist.list ; sp ; sp = sp->next) {
765 if (sep != 0)
766 outc(sep, &psh->errout);
767 out2str(psh, sp->text);
768 sep = ' ';
769 }
770 for (sp = arglist.list ; sp ; sp = sp->next) {
771 if (sep != 0)
772 outc(sep, &psh->errout);
773 out2str(psh, sp->text);
774 sep = ' ';
775 }
776 outc('\n', &psh->errout);
777 flushout(&psh->errout);
778 }
779
780 /* Now locate the command. */
781 if (argc == 0) {
782 cmdentry.cmdtype = CMDSPLBLTIN;
783 cmdentry.u.bltin = bltincmd;
784 } else {
785 static const char PATH[] = "PATH=";
786 int cmd_flags = DO_ERR;
787
788 /*
789 * Modify the command lookup path, if a PATH= assignment
790 * is present
791 */
792 for (sp = varlist.list; sp; sp = sp->next)
793 if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0)
794 path = sp->text + sizeof(PATH) - 1;
795
796 do {
797 int argsused, use_syspath;
798 find_command(psh, argv[0], &cmdentry, cmd_flags, path);
799 if (cmdentry.cmdtype == CMDUNKNOWN) {
800 psh->exitstatus = 127;
801 flushout(&psh->errout);
802 goto out;
803 }
804
805 /* implement the 'command' builtin here */
806 if (cmdentry.cmdtype != CMDBUILTIN ||
807 cmdentry.u.bltin != bltincmd)
808 break;
809 cmd_flags |= DO_NOFUNC;
810 argsused = parse_command_args(psh, argc, argv, &use_syspath);
811 if (argsused == 0) {
812 /* use 'type' builting to display info */
813 cmdentry.u.bltin = typecmd;
814 break;
815 }
816 argc -= argsused;
817 argv += argsused;
818 if (use_syspath)
819 path = syspath(psh) + 5;
820 } while (argc != 0);
821 if (cmdentry.cmdtype == CMDSPLBLTIN && cmd_flags & DO_NOFUNC)
822 /* posix mandates that 'command <splbltin>' act as if
823 <splbltin> was a normal builtin */
824 cmdentry.cmdtype = CMDBUILTIN;
825 }
826
827 /* Fork off a child process if necessary. */
828 if (cmd->ncmd.backgnd
829 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
830 || ((flags & EV_BACKCMD) != 0
831 && ((cmdentry.cmdtype != CMDBUILTIN && cmdentry.cmdtype != CMDSPLBLTIN)
832 || cmdentry.u.bltin == dotcmd
833 || cmdentry.u.bltin == evalcmd))) {
834 INTOFF;
835 jp = makejob(psh, cmd, 1);
836 mode = cmd->ncmd.backgnd;
837 if (flags & EV_BACKCMD) {
838 mode = FORK_NOJOB;
839 if (sh_pipe(psh, pip) < 0)
840 error(psh, "Pipe call failed");
841 }
842#ifdef DO_SHAREDVFORK
843 /* It is essential that if DO_SHAREDVFORK is defined that the
844 * child's address space is actually shared with the parent as
845 * we rely on this.
846 */
847 if (cmdentry.cmdtype == CMDNORMAL) {
848 pid_t pid;
849
850 savelocalvars = psh->localvars;
851 psh->localvars = NULL;
852 psh->vforked = 1;
853 switch (pid = vfork()) {
854 case -1:
855 TRACE((psh, "Vfork failed, errno=%d\n", errno));
856 INTON;
857 error(psh, "Cannot vfork");
858 break;
859 case 0:
860 /* Make sure that exceptions only unwind to
861 * after the vfork(2)
862 */
863 if (setjmp(jmploc.loc)) {
864 if (psh->exception == EXSHELLPROC) {
865 /* We can't progress with the vfork,
866 * so, set vforked = 2 so the parent
867 * knows, and _exit();
868 */
869 psh->vforked = 2;
870 sh__exit(psh, 0);
871 } else {
872 sh__exit(psh, psh->exerrno);
873 }
874 }
875 savehandler = psh->handler;
876 psh->handler = &jmploc;
877 listmklocal(psh, varlist.list, VEXPORT | VNOFUNC);
878 forkchild(psh, jp, cmd, mode, psh->vforked);
879 break;
880 default:
881 psh->handler = savehandler; /* restore from vfork(2) */
882 poplocalvars(psh);
883 psh->localvars = savelocalvars;
884 if (psh->vforked == 2) {
885 psh->vforked = 0;
886
887 (void)sh_waitpid(psh, pid, NULL, 0);
888 /* We need to progress in a normal fork fashion */
889 goto normal_fork;
890 }
891 psh->vforked = 0;
892 forkparent(psh, jp, cmd, mode, pid);
893 goto parent;
894 }
895 } else {
896normal_fork:
897#endif
898 if (forkshell(psh, jp, cmd, mode) != 0)
899 goto parent; /* at end of routine */
900 FORCEINTON;
901#ifdef DO_SHAREDVFORK
902 }
903#endif
904 if (flags & EV_BACKCMD) {
905 if (!psh->vforked) {
906 FORCEINTON;
907 }
908 shfile_close(&psh->fdtab, pip[0]);
909 if (pip[1] != 1) {
910 movefd(psh, pip[1], 1);
911 }
912 }
913 flags |= EV_EXIT;
914 }
915
916 /* This is the child process if a fork occurred. */
917 /* Execute the command. */
918 switch (cmdentry.cmdtype) {
919 case CMDFUNCTION:
920#ifdef DEBUG
921 trputs(psh, "Shell function: "); trargs(psh, argv);
922#endif
923 redirect(psh, cmd->ncmd.redirect, REDIR_PUSH);
924 saveparam = psh->shellparam;
925 psh->shellparam.malloc = 0;
926 psh->shellparam.reset = 1;
927 psh->shellparam.nparam = argc - 1;
928 psh->shellparam.p = argv + 1;
929 psh->shellparam.optnext = NULL;
930 INTOFF;
931 savelocalvars = psh->localvars;
932 psh->localvars = NULL;
933 INTON;
934 if (setjmp(jmploc.loc)) {
935 if (psh->exception == EXSHELLPROC) {
936 freeparam(psh, (volatile struct shparam *)
937 &saveparam);
938 } else {
939 freeparam(psh, &psh->shellparam);
940 psh->shellparam = saveparam;
941 }
942 poplocalvars(psh);
943 psh->localvars = savelocalvars;
944 psh->handler = savehandler;
945 longjmp(psh->handler->loc, 1);
946 }
947 savehandler = psh->handler;
948 psh->handler = &jmploc;
949 listmklocal(psh, varlist.list, 0);
950 /* stop shell blowing its stack */
951 if (++psh->funcnest > 1000)
952 error(psh, "too many nested function calls");
953 evaltree(psh, cmdentry.u.func, flags & EV_TESTED);
954 psh->funcnest--;
955 INTOFF;
956 poplocalvars(psh);
957 psh->localvars = savelocalvars;
958 freeparam(psh, &psh->shellparam);
959 psh->shellparam = saveparam;
960 psh->handler = savehandler;
961 popredir(psh);
962 INTON;
963 if (psh->evalskip == SKIPFUNC) {
964 psh->evalskip = 0;
965 psh->skipcount = 0;
966 }
967 if (flags & EV_EXIT)
968 exitshell(psh, psh->exitstatus);
969 break;
970
971 case CMDBUILTIN:
972 case CMDSPLBLTIN:
973#ifdef DEBUG
974 trputs(psh, "builtin command: "); trargs(psh, argv);
975#endif
976 mode = (cmdentry.u.bltin == execcmd) ? 0 : REDIR_PUSH;
977 if (flags == EV_BACKCMD) {
978 psh->memout.nleft = 0;
979 psh->memout.nextc = psh->memout.buf;
980 psh->memout.bufsize = 64;
981 mode |= REDIR_BACKQ;
982 }
983 e = -1;
984 savehandler = psh->handler;
985 savecmdname = psh->commandname;
986 psh->handler = &jmploc;
987 if (!setjmp(jmploc.loc)) {
988 /* We need to ensure the command hash table isn't
989 * corruped by temporary PATH assignments.
990 * However we must ensure the 'local' command works!
991 */
992 if (path != pathval(psh) && (cmdentry.u.bltin == hashcmd ||
993 cmdentry.u.bltin == typecmd)) {
994 savelocalvars = psh->localvars;
995 psh->localvars = 0;
996 mklocal(psh, path - 5 /* PATH= */, 0);
997 temp_path = 1;
998 } else
999 temp_path = 0;
1000 redirect(psh, cmd->ncmd.redirect, mode);
1001
1002 /* exec is a special builtin, but needs this list... */
1003 psh->cmdenviron = varlist.list;
1004 /* we must check 'readonly' flag for all builtins */
1005 listsetvar(psh, varlist.list,
1006 cmdentry.cmdtype == CMDSPLBLTIN ? 0 : VNOSET);
1007 psh->commandname = argv[0];
1008 /* initialize nextopt */
1009 psh->argptr = argv + 1;
1010 psh->optptr = NULL;
1011 /* and getopt */
1012#if 0 /** @todo fix getop usage! */
1013#if defined(__FreeBSD__) || defined(__EMX__) || defined(__APPLE__)
1014 optreset = 1;
1015 optind = 1;
1016#else
1017 optind = 0; /* init */
1018#endif
1019#endif
1020
1021 psh->exitstatus = cmdentry.u.bltin(psh, argc, argv);
1022 } else {
1023 e = psh->exception;
1024 psh->exitstatus = e == EXINT ? SIGINT + 128 :
1025 e == EXEXEC ? psh->exerrno : 2;
1026 }
1027 psh->handler = savehandler;
1028 output_flushall(psh);
1029 psh->out1 = &psh->output;
1030 psh->out2 = &psh->errout;
1031 freestdout(psh);
1032 if (temp_path) {
1033 poplocalvars(psh);
1034 psh->localvars = savelocalvars;
1035 }
1036 psh->cmdenviron = NULL;
1037 if (e != EXSHELLPROC) {
1038 psh->commandname = savecmdname;
1039 if (flags & EV_EXIT)
1040 exitshell(psh, psh->exitstatus);
1041 }
1042 if (e != -1) {
1043 if ((e != EXERROR && e != EXEXEC)
1044 || cmdentry.cmdtype == CMDSPLBLTIN)
1045 exraise(psh, e);
1046 FORCEINTON;
1047 }
1048 if (cmdentry.u.bltin != execcmd)
1049 popredir(psh);
1050 if (flags == EV_BACKCMD) {
1051 backcmd->buf = psh->memout.buf;
1052 backcmd->nleft = (int)(psh->memout.nextc - psh->memout.buf);
1053 psh->memout.buf = NULL;
1054 }
1055 break;
1056
1057 default:
1058#ifdef DEBUG
1059 trputs(psh, "normal command: "); trargs(psh, argv);
1060#endif
1061 clearredir(psh, psh->vforked);
1062 redirect(psh, cmd->ncmd.redirect, psh->vforked ? REDIR_VFORK : 0);
1063 if (!psh->vforked)
1064 for (sp = varlist.list ; sp ; sp = sp->next)
1065 setvareq(psh, sp->text, VEXPORT|VSTACK);
1066 envp = environment(psh);
1067 shellexec(psh, argv, envp, path, cmdentry.u.index, psh->vforked);
1068 break;
1069 }
1070 goto out;
1071
1072parent: /* parent process gets here (if we forked) */
1073 if (mode == FORK_FG) { /* argument to fork */
1074 psh->exitstatus = waitforjob(psh, jp);
1075 } else if (mode == FORK_NOJOB) {
1076 backcmd->fd = pip[0];
1077 shfile_close(&psh->fdtab, pip[1]);
1078 backcmd->jp = jp;
1079 }
1080 FORCEINTON;
1081
1082out:
1083 if (lastarg)
1084 /* dsl: I think this is intended to be used to support
1085 * '_' in 'vi' command mode during line editing...
1086 * However I implemented that within libedit itself.
1087 */
1088 setvar(psh, "_", lastarg, 0);
1089 popstackmark(psh, &smark);
1090
1091 if (eflag(psh) && psh->exitstatus && !(flags & EV_TESTED))
1092 exitshell(psh, psh->exitstatus);
1093}
1094
1095
1096/*
1097 * Search for a command. This is called before we fork so that the
1098 * location of the command will be available in the parent as well as
1099 * the child. The check for "goodname" is an overly conservative
1100 * check that the name will not be subject to expansion.
1101 */
1102
1103STATIC void
1104prehash(shinstance *psh, union node *n)
1105{
1106 struct cmdentry entry;
1107
1108 if (n->type == NCMD && n->ncmd.args)
1109 if (goodname(n->ncmd.args->narg.text))
1110 find_command(psh, n->ncmd.args->narg.text, &entry, 0,
1111 pathval(psh));
1112}
1113
1114
1115
1116/*
1117 * Builtin commands. Builtin commands whose functions are closely
1118 * tied to evaluation are implemented here.
1119 */
1120
1121/*
1122 * No command given.
1123 */
1124
1125int
1126bltincmd(shinstance *psh, int argc, char **argv)
1127{
1128 /*
1129 * Preserve psh->exitstatus of a previous possible redirection
1130 * as POSIX mandates
1131 */
1132 return psh->back_exitstatus;
1133}
1134
1135
1136/*
1137 * Handle break and continue commands. Break, continue, and return are
1138 * all handled by setting the psh->evalskip flag. The evaluation routines
1139 * above all check this flag, and if it is set they start skipping
1140 * commands rather than executing them. The variable skipcount is
1141 * the number of loops to break/continue, or the number of function
1142 * levels to return. (The latter is always 1.) It should probably
1143 * be an error to break out of more loops than exist, but it isn't
1144 * in the standard shell so we don't make it one here.
1145 */
1146
1147int
1148breakcmd(shinstance *psh, int argc, char **argv)
1149{
1150 int n = argc > 1 ? number(psh, argv[1]) : 1;
1151
1152 if (n > psh->loopnest)
1153 n = psh->loopnest;
1154 if (n > 0) {
1155 psh->evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
1156 psh->skipcount = n;
1157 }
1158 return 0;
1159}
1160
1161
1162/*
1163 * The return command.
1164 */
1165
1166int
1167returncmd(shinstance *psh, int argc, char **argv)
1168{
1169#if 0
1170 int ret = argc > 1 ? number(psh, argv[1]) : psh->exitstatus;
1171#else
1172 int ret;
1173 if (argc > 1) {
1174 /* make return -1 and VSC lite work ... */
1175 if (argv[1][0] != '-' || !is_number(&argv[1][1]))
1176 ret = number(psh, argv[1]);
1177 else
1178 ret = -number(psh, &argv[1][1]) & 255; /* take the bash approach */
1179 } else {
1180 ret = psh->exitstatus;
1181 }
1182#endif
1183
1184 if (psh->funcnest) {
1185 psh->evalskip = SKIPFUNC;
1186 psh->skipcount = 1;
1187 return ret;
1188 }
1189 else {
1190 /* Do what ksh does; skip the rest of the file */
1191 psh->evalskip = SKIPFILE;
1192 psh->skipcount = 1;
1193 return ret;
1194 }
1195}
1196
1197
1198int
1199falsecmd(shinstance *psh, int argc, char **argv)
1200{
1201 return 1;
1202}
1203
1204
1205int
1206truecmd(shinstance *psh, int argc, char **argv)
1207{
1208 return 0;
1209}
1210
1211
1212int
1213execcmd(shinstance *psh, int argc, char **argv)
1214{
1215 if (argc > 1) {
1216 struct strlist *sp;
1217
1218 iflag(psh) = 0; /* exit on error */
1219 mflag(psh) = 0;
1220 optschanged(psh);
1221 for (sp = psh->cmdenviron; sp; sp = sp->next)
1222 setvareq(psh, sp->text, VEXPORT|VSTACK);
1223 shellexec(psh, argv + 1, environment(psh), pathval(psh), 0, 0);
1224 }
1225 return 0;
1226}
1227
1228static int
1229conv_time(clock_t ticks, char *seconds, size_t l)
1230{
1231 static clock_t tpm = 0;
1232 clock_t mins;
1233 size_t i;
1234
1235 if (!tpm)
1236 tpm = /*sysconf(_SC_CLK_TCK)*/sh_sysconf_clk_tck() * 60;
1237
1238 mins = ticks / tpm;
1239#ifdef _MSC_VER
1240 {
1241 char tmp[64];
1242 sprintf(tmp, "%.4f", (ticks - mins * tpm) * 60.0 / tpm);
1243 strlcpy(seconds, tmp, l);
1244 }
1245#else
1246 snprintf(seconds, l, "%.4f", (ticks - mins * tpm) * 60.0 / tpm );
1247#endif
1248
1249 if (seconds[0] == '6' && seconds[1] == '0') {
1250 /* 59.99995 got rounded up... */
1251 mins++;
1252 strlcpy(seconds, "0.0", l);
1253 return mins;
1254 }
1255
1256 /* suppress trailing zeros */
1257 i = strlen(seconds) - 1;
1258 for (; seconds[i] == '0' && seconds[i - 1] != '.'; i--)
1259 seconds[i] = 0;
1260 return mins;
1261}
1262
1263int
1264timescmd(shinstance *psh, int argc, char **argv)
1265{
1266 shtms tms;
1267 int u, s, cu, cs;
1268 char us[8], ss[8], cus[8], css[8];
1269
1270 nextopt(psh, "");
1271
1272 sh_times(psh, &tms);
1273
1274 u = conv_time(tms.tms_utime, us, sizeof(us));
1275 s = conv_time(tms.tms_stime, ss, sizeof(ss));
1276 cu = conv_time(tms.tms_cutime, cus, sizeof(cus));
1277 cs = conv_time(tms.tms_cstime, css, sizeof(css));
1278
1279 outfmt(psh->out1, "%dm%ss %dm%ss\n%dm%ss %dm%ss\n",
1280 u, us, s, ss, cu, cus, cs, css);
1281
1282 return 0;
1283}
Note: See TracBrowser for help on using the repository browser.