reenabled swaptest. quake should now load data and start on big endian architectures...
[AROS-Contrib.git] / gnu / abc-shell / exec.c
blobb46bffbbd66e29f663c3397cd8beff7a77f08ddf
1 /*
2 * execute command tree
3 */
5 #include <ctype.h>
6 #include <sys/stat.h>
7 #include "sh.h"
8 #include "c_test.h"
9 #include <dos/dos.h>
10 #include <dos/bptr.h>
11 #include <proto/dos.h>
13 /* Does ps4 get parameter substitutions done? */
14 #define PS4_SUBSTITUTE(s) substitute((s), 0)
16 static int comexec(struct op *, struct tbl *volatile, char **,
17 int volatile);
18 static void scriptexec(struct op *, char **);
19 static int call_builtin(struct tbl *, char **);
20 static int iosetup(struct ioword *, struct tbl *);
21 static int herein(const char *, int);
22 static char *do_selectargs(char **, bool);
23 static int dbteste_isa(Test_env *, Test_meta);
24 static const char *dbteste_getopnd(Test_env *, Test_op, int);
25 static int dbteste_eval(Test_env *, Test_op, const char *, const char *,
26 int do_eval);
27 static void dbteste_error(Test_env *, int, const char *);
28 static void blk_copy(struct block *src);
29 static void tbl_copy(struct table *src, struct table *dst, Area *ap);
31 #if (0)
32 static void printflags(struct tbl *t);
33 #endif
36 * execute command tree
38 int
39 execute(struct op * volatile t,
40 volatile int flags) /* if XEXEC don't fork */
42 int i;
43 volatile int rv = 0;
44 volatile int rv_prop = 0; /* rv being propogated or newly generated? */
45 int pv[2];
46 char ** volatile ap;
47 char *s, *cp;
48 struct ioword **iowp;
49 struct tbl *tp = NULL;
51 if (t == NULL)
52 return 0;
54 /* Is this the end of a pipeline? If so, we want to evaluate the
55 * command arguments
56 bool eval_done = false;
57 if ((flags&XFORK) && !(flags&XEXEC) && (flags&XPCLOSE)) {
58 eval_done = true;
59 tp = eval_execute_args(t, &ap);
62 if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
63 return exchild(t, flags & ~XTIME, -1); /* run in sub-process */
65 newenv(E_EXEC);
67 if (trap)
68 runtraps(0);
70 if (t->type == TCOM) {
71 /* Clear subst_exstat before argument expansion. Used by
72 * null commands (see comexec() and c_eval()) and by c_set().
74 subst_exstat = 0;
76 current_lineno = t->lineno; /* for $LINENO */
78 /* POSIX says expand command words first, then redirections,
79 * and assignments last..
81 ap = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
82 if (flags & XTIME)
83 /* Allow option parsing (bizarre, but POSIX) */
84 timex_hook(t, &ap);
85 if (Flag(FXTRACE) && ap[0]) {
86 shf_fprintf(shl_out, "%s",
87 PS4_SUBSTITUTE(str_val(global("PS4"))));
88 for (i = 0; ap[i]; i++)
89 shf_fprintf(shl_out, "%s%s", ap[i],
90 ap[i + 1] ? space : newline);
91 shf_flush(shl_out);
93 if (ap[0])
94 tp = findcom(ap[0], FC_BI|FC_FUNC);
96 flags &= ~XTIME;
98 if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
99 e->savefd = (short *) alloc(sizeofN(short, NUFILE), ATEMP);
100 /* initialize to not redirected */
101 memset(e->savefd, 0, sizeofN(short, NUFILE));
104 /* do redirection, to be restored in quitenv() */
105 if (t->ioact != NULL)
106 for (iowp = t->ioact; *iowp != NULL; iowp++) {
107 if (iosetup(*iowp, tp) < 0) {
108 exstat = rv = 1;
109 /* Redirection failures for special commands
110 * cause (non-interactive) shell to exit.
112 if (tp && tp->type == CSHELL &&
113 (tp->flag & SPEC_BI))
114 errorf(null);
115 /* Deal with FERREXIT, quitenv(), etc. */
116 goto Break;
120 switch (t->type) {
121 case TCOM:
122 rv = comexec(t, tp, ap, flags);
123 break;
125 case TPAREN:
127 // rv = execute(t->left, flags|XFORK);
128 struct globals globenv;
129 copyenv(&globenv);
130 e->type = E_SUBSHELL;
131 if(!(ksh_sigsetjmp(e->jbuf,0)))
133 rv = execute(t->left, flags);
135 else
137 rv = exstat;
140 cleartraps();
141 restoreenv(&globenv);
143 rv_prop = 1;
144 break;
146 case TPIPE:
148 bool chain = false;
149 flags |= XFORK;
150 flags &= ~XEXEC;
152 e->savefd[0] = savefd(0);
153 e->savefd[1] = savefd(1);
155 while (t->type == TPIPE) {
156 openpipe(pv);
157 (void) ksh_dup2(pv[1], 1, false); /* stdout of curr */
159 /* Let exchild() close pv[0] in child
160 * (if this isn't done, commands like
161 * (: ; cat /etc/termcap) | sleep 1
162 * will hang forever).
164 exchild(t->left, flags|XPIPEO|XCCLOSE, pv[0]);
165 /* at this point if were in a chain of pipes */
166 /* then we are clsing the ouyput of the previous */
167 /* pipe. But we may not have read all data so drain it here */
168 #ifndef USE_TEMPFILES /* true pipes */
169 if(0){//chain){
171 char buffer[256];
172 int n,t;
173 t = 0;
174 while((n = read(0,buffer,sizeof(buffer)-1)) > 0) t +=n;
177 (void) ksh_dup2(pv[0], 0, false); /* stdin of next */
178 closepipe(pv);
180 #else /* temp files */
182 UBYTE pname[256];
183 BPTR f = 0;
184 if(chain)
186 __get_default_file(0,(long *)&f);
187 NameFromFH(f,pname,sizeof(pname)-1);
190 (void) ksh_dup2(pv[0], 0, false); /* stdin of next */
191 closepipe(pv);
192 if(f)
194 DeleteFile(pname);
197 #endif /* USE_TEMPFILES */
198 flags |= XPIPEI;
199 t = t->right;
200 chain=true;
203 restfd(1, e->savefd[1]); /* stdout of last */
204 e->savefd[1] = 0; /* no need to re-restore this */
205 /* Let exchild() close 0 in parent, after fork, before wait */
206 i = exchild(t, flags|XPCLOSE, 0);
207 if (!(flags&XBGND) && !(flags&XXCOM))
208 rv = i;
209 break;
212 case TLIST:
213 while (t->type == TLIST) {
214 execute(t->left, flags & XERROK);
215 t = t->right;
217 rv = execute(t, flags & XERROK);
218 break;
220 case TCOPROC:
222 sigset_t omask;
224 /* Block sigchild as we are using things changed in the
225 * signal handler
227 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
228 e->type = E_ERRH;
229 i = ksh_sigsetjmp(e->jbuf, 0);
230 if (i) {
231 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
232 quitenv(NULL);
233 unwind(i);
234 /*NOTREACHED*/
236 /* Already have a (live) co-process? */
237 if (coproc.job && coproc.write >= 0)
238 errorf("coprocess already exists");
240 /* Can we re-use the existing co-process pipe? */
241 coproc_cleanup(true);
243 /* do this before opening pipes, in case these fail */
244 e->savefd[0] = savefd(0);
245 e->savefd[1] = savefd(1);
247 openpipe(pv);
248 if (pv[0] != 0) {
249 ksh_dup2(pv[0], 0, false);
250 close(pv[0]);
252 coproc.write = pv[1];
253 coproc.job = (void *) 0;
255 if (coproc.readw >= 0)
256 ksh_dup2(coproc.readw, 1, false);
257 else {
258 openpipe(pv);
259 coproc.read = pv[0];
260 ksh_dup2(pv[1], 1, false);
261 coproc.readw = pv[1]; /* closed before first read */
262 coproc.njobs = 0;
263 /* create new coprocess id */
264 ++coproc.id;
266 sigprocmask(SIG_SETMASK, &omask, (sigset_t *) 0);
267 e->type = E_EXEC; /* no more need for error handler */
269 /* exchild() closes coproc.* in child after fork,
270 * will also increment coproc.njobs when the
271 * job is actually created.
273 flags &= ~XEXEC;
274 exchild(t->left, flags|XBGND|XFORK|XCOPROC|XCCLOSE,
275 coproc.readw);
276 break;
279 case TASYNC:
280 /* XXX non-optimal, I think - "(foo &)", forks for (),
281 * forks again for async... parent should optimize
282 * this to "foo &"...
284 rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK);
285 break;
287 case TOR:
288 case TAND:
289 rv = execute(t->left, XERROK);
290 if ((t->right != NULL) && ((rv == 0) == (t->type == TAND)))
291 rv = execute(t->right, flags & XERROK);
292 else
293 flags |= XERROK;
294 rv_prop = 1;
295 break;
297 case TBANG:
298 rv = !execute(t->right, XERROK);
299 break;
301 case TDBRACKET:
303 Test_env te;
305 te.flags = TEF_DBRACKET;
306 te.pos.wp = t->args;
307 te.isa = dbteste_isa;
308 te.getopnd = dbteste_getopnd;
309 te.eval = dbteste_eval;
310 te.error = dbteste_error;
312 rv = test_parse(&te);
313 break;
316 case TFOR:
317 case TSELECT:
319 volatile bool is_first = true;
320 ap = (t->vars != NULL) ? eval(t->vars, DOBLANK|DOGLOB|DOTILDE):
321 e->loc->argv + 1;
322 e->type = E_LOOP;
323 while (1) {
324 i = ksh_sigsetjmp(e->jbuf, 0);
325 if (!i)
326 break;
327 if ((e->flags&EF_BRKCONT_PASS) ||
328 (i != LBREAK && i != LCONTIN))
330 quitenv(NULL);
331 unwind(i);
332 } else if (i == LBREAK) {
333 rv = 0;
334 goto Break;
337 rv = 0; /* in case of a continue */
338 rv_prop = 1;
339 if (t->type == TFOR) {
340 while (*ap != NULL) {
341 setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
342 rv = execute(t->left, flags & XERROK);
344 } else { /* TSELECT */
345 for (;;) {
346 if (!(cp = do_selectargs(ap, is_first))) {
347 rv = 1;
348 rv_prop = 0;
349 break;
351 is_first = false;
352 setstr(global(t->str), cp, KSH_UNWIND_ERROR);
353 rv = execute(t->left, flags & XERROK);
357 break;
359 case TWHILE:
360 case TUNTIL:
361 e->type = E_LOOP;
362 while (1) {
363 i = ksh_sigsetjmp(e->jbuf, 0);
364 if (!i)
365 break;
366 if ((e->flags&EF_BRKCONT_PASS) ||
367 (i != LBREAK && i != LCONTIN))
369 quitenv(NULL);
370 unwind(i);
371 } else if (i == LBREAK) {
372 rv = 0;
373 goto Break;
376 rv = 0; /* in case of a continue */
377 while ((execute(t->left, XERROK) == 0) == (t->type == TWHILE))
378 rv = execute(t->right, flags & XERROK);
379 rv_prop = 1;
380 break;
382 case TIF:
383 case TELIF:
384 if (t->right == NULL)
385 break; /* should be error */
386 rv = execute(t->left, XERROK) == 0 ?
387 execute(t->right->left, flags & XERROK) :
388 execute(t->right->right, flags & XERROK);
389 rv_prop = 1;
390 break;
392 case TCASE:
393 cp = evalstr(t->str, DOTILDE);
394 for (t = t->left; t != NULL && t->type == TPAT; t = t->right)
395 for (ap = t->vars; *ap; ap++)
396 if ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
397 gmatch(cp, s, false))
398 goto Found;
399 break;
400 Found:
401 rv = execute(t->left, flags & XERROK);
402 rv_prop = 1;
403 break;
405 case TBRACE:
406 rv = execute(t->left, flags & XERROK);
407 rv_prop = 1;
408 break;
410 case TFUNCT:
411 rv = define(t->str, t);
412 break;
414 case TTIME:
415 /* Clear XEXEC so nested execute() call doesn't exit
416 * (allows "ls -l | time grep foo").
418 rv = timex(t, flags & ~XEXEC);
419 rv_prop = 1;
420 break;
422 case TEXEC: /* an eval'd TCOM */
423 s = t->args[0];
424 ap = makenv();
425 #ifndef F_SETFD
426 for (i = 0; i < sizeof(clexec_tab); i++)
427 if (clexec_tab[i]) {
428 close(i);
429 clexec_tab[i] = 0;
431 #endif
432 restoresigs();
433 cleanup_proc_env();
434 if(ksh_execve(t->str, t->args, ap, (flags & XINTACT) ? 1 : 0) < 0)
436 if (errno == ENOEXEC)
437 scriptexec(t, ap);
438 else
439 errorf("%s: %s", s, strerror(errno));
442 Break:
443 exstat = rv;
445 quitenv(NULL); /* restores IO */
446 if ((flags&XEXEC))
447 unwind(LEXIT); /* exit child */
448 if (rv != 0 && !rv_prop && !(flags & XERROK)) {
449 trapsig(SIGERR_);
450 if (Flag(FERREXIT))
451 unwind(LERROR);
453 return rv;
457 * execute simple command
460 static int
461 comexec(struct op *t, struct tbl *volatile tp, char **ap, volatile int flags)
463 int i;
464 volatile int rv = 0;
465 char *cp;
466 char **lastp;
467 int type_flags;
468 int keepasn_ok;
469 int fcflags = FC_BI|FC_FUNC|FC_PATH;
470 int bourne_function_call = 0;
472 /* snag the last argument for $_ XXX not the same as at&t ksh,
473 * which only seems to set $_ after a newline (but not in
474 * functions/dot scripts, but in interactive and script) -
475 * perhaps save last arg here and set it in shell()?.
478 if (!Flag(FSH) && Flag(FTALKING) && *(lastp = ap)) {
479 struct tbl *tb;
480 while (*++lastp);
481 tb = typeset("_", LOCAL, 0,INTEGER,0);
483 /* setstr() can't fail here */
484 setstr(tb, *--lastp, KSH_RETURN_ERROR);
487 /* Deal with the shell builtins builtin, exec and command since
488 * they can be followed by other commands. This must be done before
489 * we know if we should create a local block, which must be done
490 * before we can do a path search (in case the assignments change
491 * PATH).
492 * Odd cases:
493 * FOO=bar exec > /dev/null FOO is kept but not exported
494 * FOO=bar exec foobar FOO is exported
495 * FOO=bar command exec > /dev/null FOO is neither kept nor exported
496 * FOO=bar command FOO is neither kept nor exported
497 * PATH=... foobar use new PATH in foobar search
499 keepasn_ok = 1;
500 while (tp && tp->type == CSHELL) {
501 fcflags = FC_BI|FC_FUNC|FC_PATH;/* undo effects of command */
502 if (tp->val.f == c_builtin) {
503 if ((cp = *++ap) == NULL) {
504 tp = NULL;
505 break;
507 tp = findcom(cp, FC_BI);
508 if (tp == NULL)
509 errorf("builtin: %s: not a builtin", cp);
510 continue;
511 } else if (tp->val.f == c_exec) {
512 if (ap[1] == NULL)
513 break;
514 ap++;
515 flags |= XEXEC;
516 } else if (tp->val.f == c_command) {
517 int optc, saw_p = 0;
519 /* Ugly dealing with options in two places (here and
520 * in c_command(), but such is life)
522 ksh_getopt_reset(&builtin_opt, 0);
523 while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
524 saw_p = 1;
525 if (optc != EOF)
526 break; /* command -vV or something */
527 /* don't look for functions */
528 fcflags = FC_BI|FC_PATH;
529 if (saw_p) {
530 fcflags |= FC_DEFPATH;
532 ap += builtin_opt.optind;
533 /* POSIX says special builtins loose their status
534 * if accessed using command.
536 keepasn_ok = 0;
537 if (!ap[0]) {
538 /* ensure command with no args exits with 0 */
539 subst_exstat = 0;
540 break;
542 } else
543 break;
544 tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
546 if (keepasn_ok && (!ap[0] || (tp && (tp->flag & KEEPASN))))
547 type_flags = 0;
548 else {
549 /* create new variable/function block */
550 newblock();
551 /* ksh functions don't keep assignments, POSIX functions do. */
552 if (keepasn_ok && tp && tp->type == CFUNC
553 && !(tp->flag & FKSH)) {
554 bourne_function_call = 1;
555 type_flags = 0;
556 } else
557 type_flags = LOCAL|LOCAL_COPY|EXPORTV;
559 if (Flag(FEXPORT))
560 type_flags |= EXPORTV;
561 for (i = 0; t->vars[i]; i++) {
562 cp = evalstr(t->vars[i], DOASNTILDE);
563 if (Flag(FXTRACE)) {
564 if (i == 0)
565 shf_fprintf(shl_out, "%s",
566 PS4_SUBSTITUTE(str_val(global("PS4"))));
567 shf_fprintf(shl_out, "%s%s", cp,
568 t->vars[i + 1] ? space : newline);
569 if (!t->vars[i + 1])
570 shf_flush(shl_out);
572 typeset(cp, type_flags, 0, 0, 0);
573 if (bourne_function_call && !(type_flags & EXPORTV))
574 typeset(cp, LOCAL|LOCAL_COPY|EXPORTV, 0, 0, 0);
577 if ((cp = *ap) == NULL) {
578 rv = subst_exstat;
579 goto Leave;
580 } else if (!tp) {
581 tp = findcom(cp, fcflags);
584 switch (tp->type) {
585 case CSHELL: /* shell built-in */
586 rv = call_builtin(tp, ap);
587 break;
589 case CFUNC: /* function call */
591 volatile int old_xflag;
592 volatile Tflag old_inuse;
593 const char *volatile old_kshname;
595 if (!(tp->flag & ISSET)) {
596 struct tbl *ftp;
598 if (!tp->u.fpath) {
599 if (tp->u2.errno_) {
600 warningf(true,
601 "%s: can't find function definition file - %s",
602 cp, strerror(tp->u2.errno_));
603 rv = 126;
604 } else {
605 warningf(true,
606 "%s: can't find function definition file", cp);
607 rv = 127;
609 break;
611 if (include(tp->u.fpath, 0, (char **) 0, 0) < 0) {
612 warningf(true,
613 "%s: can't open function definition file %s - %s",
614 cp, tp->u.fpath, strerror(errno));
615 rv = 127;
616 break;
618 if (!(ftp = findfunc(cp, hash(cp), false)) ||
619 !(ftp->flag & ISSET))
621 warningf(true,
622 "%s: function not defined by %s",
623 cp, tp->u.fpath);
624 rv = 127;
625 break;
627 tp = ftp;
630 /* ksh functions set $0 to function name, POSIX functions leave
631 * $0 unchanged.
633 old_kshname = kshname;
634 if (tp->flag & FKSH)
635 kshname = ap[0];
636 else
637 ap[0] = (char *) kshname;
638 e->loc->argv = ap;
639 for (i = 0; *ap++ != NULL; i++)
641 e->loc->argc = i - 1;
642 /* ksh-style functions handle getopts sanely,
643 * bourne/posix functions are insane...
645 if (tp->flag & FKSH) {
646 e->loc->flags |= BF_DOGETOPTS;
647 e->loc->getopts_state = user_opt;
648 getopts_reset(1);
651 old_xflag = Flag(FXTRACE);
652 Flag(FXTRACE) = tp->flag & TRACE ? true : false;
654 old_inuse = tp->flag & FINUSE;
655 tp->flag |= FINUSE;
657 e->type = E_FUNC;
658 i = ksh_sigsetjmp(e->jbuf, 0);
659 if (i == 0) {
660 /* seems odd to pass XERROK here, but at&t ksh does */
661 exstat = execute(tp->val.t, flags & XERROK);
662 i = LRETURN;
664 kshname = old_kshname;
665 Flag(FXTRACE) = old_xflag;
666 tp->flag = (tp->flag & ~FINUSE) | old_inuse;
667 /* Were we deleted while executing? If so, free the execution
668 * tree. todo: Unfortunately, the table entry is never re-used
669 * until the lookup table is expanded.
671 if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
672 if (tp->flag & ALLOC) {
673 tp->flag &= ~ALLOC;
674 tfree(tp->val.t, tp->areap);
676 tp->flag = 0;
678 switch (i) {
679 case LRETURN:
680 case LERROR:
681 rv = exstat;
682 break;
683 case LINTR:
684 case LEXIT:
685 case LLEAVE:
686 case LSHELL:
687 quitenv(NULL);
688 unwind(i);
689 /*NOTREACHED*/
690 default:
691 quitenv(NULL);
692 internal_errorf(1, "CFUNC %d", i);
694 break;
697 case CEXEC: /* executable command */
699 case CTALIAS: /* tracked alias */
700 if (!(tp->flag&ISSET)) {
701 /* errno_ will be set if the named command was found
702 * but could not be executed (permissions, no execute
703 * bit, directory, etc). Print out a (hopefully)
704 * useful error message and set the exit status to 126.
706 if (tp->u2.errno_) {
707 warningf(true, "%s: cannot execute - %s", cp,
708 strerror(tp->u2.errno_));
709 rv = 126; /* POSIX */
710 } else {
711 warningf(true, "%s: not found", cp);
712 rv = 127;
714 break;
717 if (!Flag(FSH)) {
718 /* set $_ to program's full path */
719 /* setstr() can't fail here */
720 setstr(typeset("_", LOCAL|EXPORTV, 0, INTEGER, 0), tp->val.s,
721 KSH_RETURN_ERROR);
724 if (flags&XEXEC) {
725 j_exit();
726 if (!(flags&XBGND)) {
727 setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
728 setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
732 /* to fork we set up a TEXEC node and call execute */
733 struct op texec;
734 memset(&texec, 0, sizeof(struct op));
735 texec.type = TEXEC;
736 texec.left = t; /* for tprint */
737 texec.str = tp->val.s;
738 texec.args = ap;
741 rv = exchild(&texec, flags, -1);
742 break;
744 Leave:
745 if (flags & XEXEC) {
746 exstat = rv;
747 unwind(LLEAVE);
749 return rv;
752 static void
753 scriptexec(struct op *tp, char **ap)
755 char *shell;
757 shell = str_val(global(EXECSHELL_STR));
758 if (shell && *shell)
759 shell = search(shell, path, X_OK, (int *) 0);
760 if (!shell || !*shell)
761 shell = strdup(EXECSHELL);
763 *tp->args-- = tp->str;
764 *tp->args = shell;
766 if(execve(tp->args[0], tp->args, ap) < 0)
768 /* report both the program that was run and the bogus shell */
769 errorf("%s: %s: %s", tp->str, shell, strerror(errno));
774 shcomexec(char **wp)
776 struct tbl *tp;
778 tp = ktsearch(&builtins, *wp, hash(*wp));
779 if (tp == NULL)
780 internal_errorf(1, "shcomexec: %s", *wp);
781 return call_builtin(tp, wp);
785 * Search function tables for a function. If create set, a table entry
786 * is created if none is found.
788 struct tbl *
789 findfunc(const char *name, unsigned int h, int create)
791 struct block *l;
792 struct tbl *tp = (struct tbl *) 0;
794 for (l = e->loc; l; l = l->next) {
795 tp = ktsearch(&l->funs, name, h);
796 if (tp)
797 break;
798 if (!l->next && create) {
799 tp = ktenter(&l->funs, name, h);
800 tp->flag = DEFINED;
801 tp->type = CFUNC;
802 tp->val.t = (struct op *) 0;
803 break;
806 return tp;
810 * define function. Returns 1 if function is being undefined (t == 0) and
811 * function did not exist, returns 0 otherwise.
814 define(const char *name, struct op *t)
816 struct tbl *tp;
817 int was_set = 0;
819 while (1) {
820 tp = findfunc(name, hash(name), true);
822 if (tp->flag & ISSET)
823 was_set = 1;
824 /* If this function is currently being executed, we zap this
825 * table entry so findfunc() won't see it
827 if (tp->flag & FINUSE) {
828 tp->name[0] = '\0';
829 tp->flag &= ~DEFINED; /* ensure it won't be found */
830 tp->flag |= FDELETE;
831 } else
832 break;
835 if (tp->flag & ALLOC) {
836 tp->flag &= ~(ISSET|ALLOC);
837 tfree(tp->val.t, tp->areap);
840 if (t == NULL) { /* undefine */
841 ktdelete(tp);
842 return was_set ? 0 : 1;
845 tp->val.t = tcopy(t->left, tp->areap);
846 tp->flag |= (ISSET|ALLOC);
847 if (t->u.ksh_func)
848 tp->flag |= FKSH;
850 return 0;
854 * add builtin
856 void
857 builtin(const char *name, int (*func) (char **))
859 struct tbl *tp;
860 Tflag flag;
862 /* see if any flags should be set for this builtin */
863 for (flag = 0; ; name++) {
864 if (*name == '=') /* command does variable assignment */
865 flag |= KEEPASN;
866 else if (*name == '*') /* POSIX special builtin */
867 flag |= SPEC_BI;
868 else if (*name == '+') /* POSIX regular builtin */
869 flag |= REG_BI;
870 else
871 break;
874 tp = ktenter(&builtins, name, hash(name));
875 tp->flag = DEFINED | flag;
876 tp->type = CSHELL;
877 tp->val.f = func;
881 * find command
882 * either function, hashed command, or built-in (in that order)
884 struct tbl *
885 findcom(const char *name, int flags)
887 static struct tbl temp;
888 unsigned int h = hash(name);
889 struct tbl *tp = NULL, *tbi;
890 int insert = Flag(FTRACKALL); /* insert if not found */
891 char *fpath; /* for function autoloading */
892 char *npath;
894 if (ksh_strchr_dirsep(name) != NULL) {
895 insert = 0;
896 /* prevent FPATH search below */
897 flags &= ~FC_FUNC;
898 goto Search;
900 tbi = (flags & FC_BI) ? ktsearch(&builtins, name, h) : NULL;
901 /* POSIX says special builtins first, then functions, then
902 * POSIX regular builtins, then search path...
904 if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
905 tp = tbi;
906 if (!tp && (flags & FC_FUNC)) {
907 tp = findfunc(name, h, false);
908 if (tp && !(tp->flag & ISSET)) {
909 if ((fpath = str_val(global("FPATH"))) == null) {
910 tp->u.fpath = (char *) 0;
911 tp->u2.errno_ = 0;
912 } else
913 tp->u.fpath = search(name, fpath, R_OK,
914 &tp->u2.errno_);
917 if (!tp && (flags & FC_REGBI) && tbi && (tbi->flag & REG_BI))
918 tp = tbi;
919 /* todo: posix says non-special/non-regular builtins must
920 * be triggered by some user-controllable means like a
921 * special directory in PATH. Requires modifications to
922 * the search() function. Tracked aliases should be
923 * modified to allow tracking of builtin commands.
924 * This should be under control of the FPOSIX flag.
925 * If this is changed, also change c_whence...
927 if (!tp && (flags & FC_UNREGBI) && tbi)
928 tp = tbi;
929 if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
930 tp = ktsearch(taliases, name, h);
931 if (tp && (tp->flag & ISSET) && eaccess(tp->val.s, X_OK) != 0) {
932 if (tp->flag & ALLOC) {
933 tp->flag &= ~ALLOC;
934 afree(tp->val.s, APERM);
936 tp->flag &= ~ISSET;
940 Search:
941 if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
942 (flags & FC_PATH))
944 if (!tp) {
945 if (insert && !(flags & FC_DEFPATH)) {
946 tp = ktenter(taliases, name, h);
947 tp->type = CTALIAS;
948 } else {
949 tp = &temp;
950 tp->type = CEXEC;
952 tp->flag = DEFINED; /* make ~ISSET */
954 npath = search(name, flags & FC_DEFPATH ? def_path : path,
955 X_OK, &tp->u2.errno_);
956 if (npath) {
957 if (tp == &temp) {
958 tp->val.s = npath;
959 } else {
960 tp->val.s = str_save(npath, APERM);
961 if (npath != name)
962 afree(npath, ATEMP);
964 tp->flag |= ISSET|ALLOC;
965 } else if ((flags & FC_FUNC)
966 && (fpath = str_val(global("FPATH"))) != null
967 && (npath = search(name, fpath, R_OK,
968 &tp->u2.errno_)) != (char *) 0)
970 /* An undocumented feature of at&t ksh is that it
971 * searches FPATH if a command is not found, even
972 * if the command hasn't been set up as an autoloaded
973 * function (ie, no typeset -uf).
975 tp = &temp;
976 tp->type = CFUNC;
977 tp->flag = DEFINED; /* make ~ISSET */
978 tp->u.fpath = npath;
981 return tp;
985 * flush executable commands with relative paths
987 void
988 flushcom(int all) /* just relative or all */
990 struct tbl *tp;
991 struct tstate ts;
993 for (ktwalk(&ts, taliases); (tp = ktnext(&ts)) != NULL; )
994 if ((tp->flag&ISSET) && (all || !ISDIRSEP(tp->val.s[0]))) {
995 if (tp->flag&ALLOC) {
996 tp->flag &= ~(ALLOC|ISSET);
997 afree(tp->val.s, APERM);
999 tp->flag &= ~ISSET;
1003 /* Check if path is something we want to find. Returns -1 for failure. */
1005 search_access(const char *path, int mode,
1006 int *errnop) /* set if candidate found, but not suitable */
1008 int ret, err = 0;
1009 struct stat statb;
1011 if (stat(path, &statb) < 0)
1012 return -1;
1013 ret = eaccess(path, mode);
1014 if (ret < 0)
1015 err = errno; /* File exists, but we can't access it */
1016 else if (mode == X_OK
1017 && (!S_ISREG(statb.st_mode)
1018 /* This 'cause access() says root can execute everything */
1019 || !(statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))))
1021 ret = -1;
1022 err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
1024 if (err && errnop && !*errnop)
1025 *errnop = err;
1026 return ret;
1030 * search for command with PATH
1032 char *
1033 search(const char *name, const char *path,
1034 int mode, /* R_OK or X_OK */
1035 int *errnop) /* set if candidate found, but not suitable */
1037 const char *sp, *p;
1038 char *xp;
1039 XString xs;
1040 int namelen;
1042 if (errnop)
1043 *errnop = 0;
1044 if (ksh_strchr_dirsep(name)) {
1045 if (search_access(name, mode, errnop) == 0)
1047 #ifdef AMIGA
1048 if((name[0] == '.') && (name[1] == '/'))
1049 return (char *) &name[2];
1050 #endif
1051 return (char *) name;
1053 return NULL;
1056 namelen = strlen(name) + 1;
1057 Xinit(xs, xp, 128, ATEMP);
1059 sp = path;
1060 while (sp != NULL) {
1061 xp = Xstring(xs, xp);
1062 if (!(p = strchr(sp, PATHSEP)))
1063 p = sp + strlen(sp);
1064 if (p != sp) {
1065 XcheckN(xs, xp, p - sp);
1066 memcpy(xp, sp, p - sp);
1067 xp += p - sp;
1068 *xp++ = DIRSEP;
1070 sp = p;
1071 XcheckN(xs, xp, namelen);
1072 memcpy(xp, name, namelen);
1073 if (search_access(Xstring(xs, xp), mode, errnop) == 0)
1075 #ifdef AMIGA
1076 sp = Xclose(xs, xp + namelen);
1077 if((sp[0] == '.') && (sp[1] == '/') && !strcmp(&sp[2], name))
1079 sp =strdup(name);
1080 Xfree(xs, xp);
1082 return (char *) sp;
1083 #else
1084 return Xclose(xs, xp + namelen);
1085 #endif
1087 if (*sp++ == '\0')
1088 sp = NULL;
1090 Xfree(xs, xp);
1091 return NULL;
1094 static int
1095 call_builtin(struct tbl *tp, char **wp)
1097 int rv;
1099 builtin_argv0 = wp[0];
1100 builtin_flag = tp->flag;
1101 shf_reopen(1, SHF_WR, shl_stdout);
1102 shl_stdout_ok = 1;
1103 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1104 rv = (*tp->val.f)(wp);
1105 shf_flush(shl_stdout);
1106 shl_stdout_ok = 0;
1107 builtin_flag = 0;
1108 builtin_argv0 = (char *) 0;
1109 return rv;
1113 * set up redirection, saving old fd's in e->savefd
1115 static int
1116 iosetup(struct ioword *iop, struct tbl *tp)
1118 int u = -1;
1119 char *cp = iop->name;
1120 int iotype = iop->flag & IOTYPE;
1121 int do_open = 1, do_close = 0, flags = 0;
1122 struct ioword iotmp;
1123 struct stat statb;
1125 if (iotype != IOHERE)
1126 cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1128 /* Used for tracing and error messages to print expanded cp */
1129 iotmp = *iop;
1130 iotmp.name = (iotype == IOHERE) ? (char *) 0 : cp;
1131 iotmp.flag |= IONAMEXP;
1133 if (Flag(FXTRACE))
1134 shellf("%s%s\n",
1135 PS4_SUBSTITUTE(str_val(global("PS4"))),
1136 snptreef((char *) 0, 32, "%R", &iotmp));
1138 switch (iotype) {
1139 case IOREAD:
1140 flags = O_RDONLY;
1141 break;
1143 case IOCAT:
1144 flags = O_WRONLY | O_APPEND | O_CREAT;
1145 break;
1147 case IOWRITE:
1148 flags = O_WRONLY | O_CREAT | O_TRUNC;
1149 /* The stat() is here to allow redirections to
1150 * things like /dev/null without error.
1152 if (Flag(FNOCLOBBER) && !(iop->flag & IOCLOB)
1153 && (stat(cp, &statb) < 0 || S_ISREG(statb.st_mode)))
1154 flags |= O_EXCL;
1155 break;
1157 case IORDWR:
1158 flags = O_RDWR | O_CREAT;
1159 break;
1161 case IOHERE:
1162 do_open = 0;
1163 /* herein() returns -2 if error has been printed */
1164 u = herein(iop->heredoc, iop->flag & IOEVAL);
1165 /* cp may have wrong name */
1166 break;
1168 case IODUP:
1170 const char *emsg;
1172 do_open = 0;
1173 if (*cp == '-' && !cp[1]) {
1174 u = 1009; /* prevent error return below */
1175 do_close = 1;
1176 } else if ((u = check_fd(cp,
1177 X_OK | ((iop->flag & IORDUP) ? R_OK : W_OK),
1178 &emsg)) < 0)
1180 warningf(true, "%s: %s",
1181 snptreef((char *) 0, 32, "%R", &iotmp), emsg);
1182 return -1;
1184 if (u == iop->unit)
1185 return 0; /* "dup from" == "dup to" */
1186 break;
1189 if (do_open) {
1190 u = open(cp, flags, 0666);
1192 if (u < 0) {
1193 /* herein() may already have printed message */
1194 if (u == -1)
1195 warningf(true, "cannot %s %s: %s",
1196 iotype == IODUP ? "dup"
1197 : (iotype == IOREAD || iotype == IOHERE) ?
1198 "open" : "create", cp, strerror(errno));
1199 return -1;
1201 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1202 if (e->savefd[iop->unit] == 0) {
1203 /* c_exec() assumes e->savefd[fd] set for any redirections.
1204 * Ask savefd() not to close iop->unit - allows error messages
1205 * to be seen if iop->unit is 2; also means we can't lose
1206 * the fd (eg, both dup2 below and dup2 in restfd() failing).
1208 e->savefd[iop->unit] = savefd(iop->unit);
1211 if (do_close)
1212 close(iop->unit);
1213 else if (u != iop->unit) {
1214 if (ksh_dup2(u, iop->unit, true) < 0) {
1215 warningf(true,
1216 "could not finish (dup) redirection %s: %s",
1217 snptreef((char *) 0, 32, "%R", &iotmp),
1218 strerror(errno));
1219 if (iotype != IODUP)
1220 close(u);
1221 return -1;
1223 if (iotype != IODUP)
1224 close(u);
1225 /* Touching any co-process fd in an empty exec
1226 * causes the shell to close its copies
1228 else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1229 if (iop->flag & IORDUP) /* possible exec <&p */
1230 coproc_read_close(u);
1231 else /* possible exec >&p */
1232 coproc_write_close(u);
1235 if (u == 2) /* Clear any write errors */
1236 shf_reopen(2, SHF_WR, shl_out);
1237 return 0;
1241 * open here document temp file.
1242 * if unquoted here, expand here temp file into second temp file.
1244 static int
1245 herein(const char *content, int sub)
1247 volatile int fd = -1;
1248 struct source *s, *volatile osource;
1249 struct shf *volatile shf;
1250 struct temp *h;
1251 int i;
1253 /* ksh -c 'cat << EOF' can cause this... */
1254 if (content == (char *) 0) {
1255 warningf(true, "here document missing");
1256 return -2; /* special to iosetup(): don't print error */
1259 /* Create temp file to hold content (done before newenv so temp
1260 * doesn't get removed too soon).
1262 h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1263 if (!(shf = h->shf) || (fd = open(h->name, O_RDONLY, 0)) < 0) {
1264 warningf(true, "can't %s temporary file %s: %s",
1265 !shf ? "create" : "open",
1266 h->name, strerror(errno));
1267 if (shf)
1268 shf_close(shf);
1269 return -2 /* special to iosetup(): don't print error */;
1272 osource = source;
1273 newenv(E_ERRH);
1274 i = ksh_sigsetjmp(e->jbuf, 0);
1275 if (i) {
1276 source = osource;
1277 quitenv(shf);
1278 shf_close(shf); /* after quitenv */
1279 close(fd);
1280 return -2; /* special to iosetup(): don't print error */
1282 if (sub) {
1283 /* Do substitutions on the content of heredoc */
1284 s = pushs(SSTRING, ATEMP);
1285 s->start = s->str = content;
1286 source = s;
1287 if (yylex(ONEWORD) != LWORD)
1288 internal_errorf(1, "herein: yylex");
1289 source = osource;
1290 shf_puts(evalstr(yylval.cp, 0), shf);
1291 } else
1292 shf_puts(content, shf);
1294 quitenv(NULL);
1296 if (shf_close(shf) == EOF) {
1297 close(fd);
1298 warningf(true, "error writing %s: %s", h->name,
1299 strerror(errno));
1300 return -2; /* special to iosetup(): don't print error */
1303 return fd;
1307 * ksh special - the select command processing section
1308 * print the args in column form - assuming that we can
1310 static char *
1311 do_selectargs(char **ap, bool print_menu)
1313 static const char *const read_args[] = {
1314 "read", "-r", "REPLY", (char *) 0
1316 char *s;
1317 int i, argct;
1319 for (argct = 0; ap[argct]; argct++)
1321 while (1) {
1322 /* Menu is printed if
1323 * - this is the first time around the select loop
1324 * - the user enters a blank line
1325 * - the REPLY parameter is empty
1327 if (print_menu || !*str_val(global("REPLY")))
1328 pr_menu(ap);
1329 shellf("%s", str_val(global("PS3")));
1330 if (call_builtin(findcom("read", FC_BI), (char **) read_args))
1331 return (char *) 0;
1332 s = str_val(global("REPLY"));
1333 if (*s) {
1334 i = atoi(s);
1335 return (i >= 1 && i <= argct) ? ap[i - 1] : null;
1337 print_menu = 1;
1341 struct select_menu_info {
1342 char *const *args;
1343 int arg_width;
1344 int num_width;
1347 static char *select_fmt_entry(void *arg, int i, char *buf, int buflen);
1349 /* format a single select menu item */
1350 static char *
1351 select_fmt_entry(void *arg, int i, char *buf, int buflen)
1353 struct select_menu_info *smi = (struct select_menu_info *) arg;
1355 shf_snprintf(buf, buflen, "%*d) %s",
1356 smi->num_width, i + 1, smi->args[i]);
1357 return buf;
1361 * print a select style menu
1364 pr_menu(char *const *ap)
1366 struct select_menu_info smi;
1367 char *const *pp;
1368 int nwidth, dwidth;
1369 int i, n;
1371 /* Width/column calculations were done once and saved, but this
1372 * means select can't be used recursively so we re-calculate each
1373 * time (could save in a structure that is returned, but its probably
1374 * not worth the bother).
1378 * get dimensions of the list
1380 for (n = 0, nwidth = 0, pp = ap; *pp; n++, pp++) {
1381 i = strlen(*pp);
1382 nwidth = (i > nwidth) ? i : nwidth;
1385 * we will print an index of the form
1386 * %d)
1387 * in front of each entry
1388 * get the max width of this
1390 for (i = n, dwidth = 1; i >= 10; i /= 10)
1391 dwidth++;
1393 smi.args = ap;
1394 smi.arg_width = nwidth;
1395 smi.num_width = dwidth;
1396 print_columns(shl_out, n, select_fmt_entry, (void *) &smi,
1397 dwidth + nwidth + 2, 1);
1399 return n;
1402 /* XXX: horrible kludge to fit within the framework */
1404 static char *plain_fmt_entry(void *arg, int i, char *buf, int buflen);
1406 static char *
1407 plain_fmt_entry(void *arg, int i, char *buf, int buflen)
1409 shf_snprintf(buf, buflen, "%s", ((char *const *)arg)[i]);
1410 return buf;
1414 pr_list(char *const *ap)
1416 char *const *pp;
1417 int nwidth;
1418 int i, n;
1420 for (n = 0, nwidth = 0, pp = ap; *pp; n++, pp++) {
1421 i = strlen(*pp);
1422 nwidth = (i > nwidth) ? i : nwidth;
1424 print_columns(shl_out, n, plain_fmt_entry, (void *) ap, nwidth + 1, 0);
1426 return n;
1430 * [[ ... ]] evaluation routines
1433 extern const char *const dbtest_tokens[];
1434 extern const char db_close[];
1436 /* Test if the current token is a whatever. Accepts the current token if
1437 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1438 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1440 static int
1441 dbteste_isa(Test_env *te, Test_meta meta)
1443 int ret = 0;
1444 int uqword;
1445 char *p;
1447 if (!*te->pos.wp)
1448 return meta == TM_END;
1450 /* unquoted word? */
1451 for (p = *te->pos.wp; *p == CHAR; p += 2)
1453 uqword = *p == EOS;
1455 if (meta == TM_UNOP || meta == TM_BINOP) {
1456 if (uqword) {
1457 char buf[8]; /* longer than the longest operator */
1458 char *q = buf;
1459 for (p = *te->pos.wp;
1460 *p == CHAR && q < &buf[sizeof(buf) - 1]; p += 2)
1461 *q++ = p[1];
1462 *q = '\0';
1463 ret = (int) test_isop(te, meta, buf);
1465 } else if (meta == TM_END)
1466 ret = 0;
1467 else
1468 ret = uqword &&
1469 strcmp(*te->pos.wp, dbtest_tokens[(int) meta]) == 0;
1471 /* Accept the token? */
1472 if (ret)
1473 te->pos.wp++;
1475 return ret;
1478 static const char *
1479 dbteste_getopnd(Test_env *te, Test_op op, int do_eval)
1481 char *s = *te->pos.wp;
1483 if (!s)
1484 return (char *) 0;
1486 te->pos.wp++;
1488 if (!do_eval)
1489 return null;
1491 if (op == TO_STEQL || op == TO_STNEQ)
1492 s = evalstr(s, DOTILDE | DOPAT);
1493 else
1494 s = evalstr(s, DOTILDE);
1496 return s;
1499 static int
1500 dbteste_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
1501 int do_eval)
1503 return test_eval(te, op, opnd1, opnd2, do_eval);
1506 static void
1507 dbteste_error(Test_env *te, int offset, const char *msg)
1509 te->flags |= TEF_ERROR;
1510 internal_errorf(0, "dbteste_error: %s (offset %d)", msg, offset);
1514 /* have to copy stuff lacking fork () */
1515 void
1516 blk_copy(struct block *src)
1518 /* this is the deepest nested block, also called `globals' */
1519 if (src->next)
1520 blk_copy(src->next);
1522 newblock();
1523 struct block *l = e->loc;
1524 l->argc = src->argc;
1526 if (l->argc) {
1527 /* copy the argument vector */
1528 char **tw, **rw;
1529 for (tw = src->argv; *tw++ != NULL; ) ;
1530 rw = l->argv = alloc((int)(tw - src->argv) * sizeof(*tw), &l->area);
1531 for (tw = src->argv; *tw != NULL; )
1533 *rw++ = wdcopy(*tw++, &l->area);
1535 *rw = NULL;
1537 else {
1538 static char *empty[] = {NULL};
1539 l->argv = (char **)empty;
1540 l->argv[0] = src->argv[0]; /* preserve only $0 */
1543 tbl_copy(&src->vars, &l->vars, &l->area);
1544 tbl_copy(&src->funs, &l->funs, &l->area);
1546 /* they're not used anyway (ie. always 0), but something like this
1547 will have to be done when they ARE used. Perhaps it will be ATEMP
1548 instead of APERM? */
1549 l->error = src->error ? str_save(src->error, APERM) : 0;
1550 l->exit = src->exit ? str_save(src->exit, APERM) : 0;
1554 void
1555 tbl_copy(struct table *src, struct table *dst, Area *ap)
1557 struct tbl *t;
1558 struct tstate ts;
1560 ktwalk(&ts,src);
1561 ktinit(dst, ap, 0);
1562 while ((t = ktnext(&ts))) {
1563 struct tbl *tn = ktenter(dst, t->name, hash(t->name));
1564 tn->flag = t->flag;
1565 tn->type = t->type;
1566 if (t->flag & INTEGER)
1567 tn->val.i = t->val.i;
1568 else if (t->flag & EXPORTV)
1569 tn->val.s = str_save(t->val.s, ap);
1570 else if (t->type == CFUNC)
1571 tn->val.t = t->val.t ? tcopy(t->val.t, ap) : 0;
1572 else
1573 tn->val.s = (t->flag & ALLOC) ? str_save(t->val.s, ap) : 0;
1575 tn->index = t->index;
1576 tn->areap = ap;
1578 tn->u2.field = t->u2.field;
1579 if (t->flag & ARRAY) {
1580 struct tbl *tmp, **list = &tn->u.array;
1581 *list = NULL;
1582 for (tmp = t->u.array; tmp; tmp = tmp->u.array) {
1583 int size = sizeof(struct tbl) + strlen(tmp->name) + 1;
1584 struct tbl *new;
1586 *list = new = (struct tbl *)alloc(size, ap);
1587 memcpy(new, tmp, size);
1588 new->areap = ap;
1589 if (tmp->flag & ALLOC)
1590 new->val.s = str_save(tmp->val.s, ap);
1592 list = &new->u.array;
1596 tn->u.array = t->u.array;
1597 if ((tn->flag & SPECIAL) && !strcmp(tn->name, "PATH"))
1598 path = str_save(tn->val.s + tn->type, ap);
1603 void
1604 copyenv(struct globals *globenv )
1606 /* first set everything to a known state */
1607 memset(globenv, 0, sizeof(struct globals));
1609 /* save pointers to current environment */
1610 globenv->aperm = aperm;
1611 globenv->e = e;
1612 globenv->homedirs = homedirs;
1613 globenv->aliases = aliases;
1614 globenv->taliases = taliases;
1615 globenv->path = path; /* will be copied in tbl_copy */
1616 globenv->current_wd = current_wd;
1617 globenv->current_wd_size = current_wd_size;
1619 /* set up new "permanent storage" */
1620 aperm = malloc(sizeof(Area));
1621 if ( aperm == NULL ) {
1622 internal_errorf(1, "out of memory");
1624 else {
1625 ainit(aperm);
1628 homedirs = malloc(sizeof(struct table));
1629 taliases = malloc(sizeof(struct table));
1630 aliases = malloc(sizeof(struct table));
1631 if ( homedirs == NULL || taliases == NULL || aliases == NULL ) {
1632 internal_errorf(1, "out of memory");
1635 ktinit(taliases, APERM, 0);
1636 ktinit(aliases, APERM, 0);
1637 ktinit(homedirs, APERM, 0);
1639 /* setup base environment */
1640 struct env *copy = malloc(sizeof(struct env));
1641 if ( copy == NULL ) {
1642 internal_errorf(1, "out of memory");
1645 memset(copy, 0, sizeof(struct env));
1646 copy->type = E_NONE;
1647 ainit(&copy->area);
1649 tbl_copy(globenv->homedirs, homedirs, APERM);
1650 tbl_copy(globenv->taliases, taliases, APERM);
1651 tbl_copy(globenv->aliases, aliases, APERM);
1653 struct block *b = e->loc;
1654 short *old = e->savefd;
1656 /* now transfer environment, and use the copy */
1657 e = copy;
1658 blk_copy(b);
1660 if (old) {
1661 size_t size = sizeofN(short, NUFILE);
1662 e->savefd = (short*) alloc(size, ATEMP);
1663 memcpy(e->savefd, old, size);
1666 /* setup the current_wd in our new APERM */
1667 current_wd = NULL;
1668 current_wd_size = 0;
1669 set_current_wd(globenv->current_wd);
1671 /* duplicate and save file handles */
1672 int i;
1673 for( i=0; i<NUFILE;i++) {
1674 globenv->fd[i] = savefd(i);
1677 /* copy the current state of the ctypes array */
1678 memcpy(globenv->ctypes, ctypes, UCHAR_MAX+1);
1680 /* copy the sigtraps and clear them for use by subshell */
1681 memcpy(globenv->sigtraps, sigtraps, sizeof(sigtraps));
1682 for (i = 0; i < (NSIG+1); i++) {
1683 sigtraps[i].trap = 0;
1684 sigtraps[i].set = 0;
1685 sigtraps[i].flags = 0;
1686 sigtraps[i].cursig = 0;
1687 sigtraps[i].shtrap = 0;
1690 /* note other stuff nay need doing! */
1694 void
1695 restoreenv(struct globals *globenv)
1697 /* free copy environment and it's ATEMP */
1698 struct block *l = e->loc;
1699 for(;l;l=l->next) {
1700 afreeall(&l->area);
1703 afreeall(&e->area);
1704 free(e);
1706 /* simply free the aperm area */
1707 afreeall(aperm);
1708 free(aperm);
1709 free(homedirs);
1710 free(taliases);
1711 free(aliases);
1713 /* restore old tables and environment */
1714 aperm = globenv->aperm;
1715 e = globenv->e;
1716 homedirs = globenv->homedirs;
1717 aliases = globenv->aliases;
1718 taliases = globenv->taliases;
1719 path = globenv->path;
1721 /* restore working dir */
1722 current_wd = globenv->current_wd;
1723 current_wd_size = globenv->current_wd_size;
1724 (void) chdir(current_wd);
1726 /* restore duplicated file handles */
1727 int i;
1728 for( i=0; i<NUFILE;i++) {
1729 if(globenv->fd[i] >= 0)
1730 restfd(i,globenv->fd[i]);
1733 /* restore ctypes array */
1734 memcpy(ctypes,globenv->ctypes,UCHAR_MAX + 1);
1736 /* copy the sigtraps and clear them for use by subshell */
1737 memcpy(sigtraps, globenv->sigtraps, sizeof(sigtraps));
1740 #if(0)
1741 void printflags(struct tbl *t)
1743 printf(" flags %d ",t->flag);
1744 if(t->flag & ALLOC) printf("ALLOC ");
1745 if(t->flag & DEFINED) printf("DEFINED ");
1746 if(t->flag & ISSET) printf("ISSET ");
1747 if(t->flag & EXPORTV) printf("EXPORTV ");
1748 if(t->flag & TRACE) printf("TRACE ");
1749 if(t->flag & SPECIAL) printf("SPECIAL ");
1750 if(t->flag & INTEGER) printf("INTEGER ");
1751 if(t->flag & RDONLY) printf("RDONLY ");
1752 if(t->flag & LOCAL) printf("LOCAL ");
1753 if(t->flag & ARRAY) printf("ARRAY ");
1754 if(t->flag & LJUST) printf("LJUST ");
1755 if(t->flag & RJUST) printf("RJUST ");
1756 if(t->flag & ZEROFIL) printf("ZEROFIL ");
1757 if(t->flag & LCASEV) printf("LCASEV ");
1758 if(t->flag & UCASEV_AL) printf("UCASEV_ALTRACE ");
1759 if(t->flag & INT_U) printf("INT_U ");
1760 if(t->flag & INT_L) printf("INT_L");
1761 if(t->flag & IMPORTV) printf("IMPORTV ");
1762 if(t->flag & LOCAL_COPY) printf("LOCAL_COPY ");
1763 if(t->flag & EXPRINEVAL) printf("EXPRINEVAL ");
1764 if(t->flag & EXPRLVALUE) printf("EXPRLVALUE ");
1765 printf("\n");
1768 #endif