blob: 4c7d4a1df607678714d8ba92613a4f28587226a7 [file] [log] [blame]
Thorsten Glaserba2627c2010-08-24 18:21:37 +02001/* $OpenBSD: main.c,v 1.46 2010/05/19 17:36:08 jasper Exp $ */
2/* $OpenBSD: tty.c,v 1.9 2006/03/14 22:08:01 deraadt Exp $ */
3/* $OpenBSD: io.c,v 1.22 2006/03/17 16:30:13 millert Exp $ */
4/* $OpenBSD: table.c,v 1.13 2009/01/17 22:06:44 millert Exp $ */
5
6/*-
7 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
8 * Thorsten Glaser <tg@mirbsd.org>
9 *
10 * Provided that these terms and disclaimer and all copyright notices
11 * are retained or reproduced in an accompanying document, permission
12 * is granted to deal in this work without restriction, including un-
13 * limited rights to use, publicly perform, distribute, sell, modify,
14 * merge, give away, or sublicence.
15 *
16 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
17 * the utmost extent permitted by applicable law, neither express nor
18 * implied; without malicious intent or gross negligence. In no event
19 * may a licensor, author or contributor be held liable for indirect,
20 * direct, other damage, loss, or other issues arising in any way out
21 * of dealing in the work, even if advised of the possibility of such
22 * damage or existence of a defect, except proven that it results out
23 * of said person's immediate fault when using the work as intended.
24 */
25
26#define EXTERN
27#include "sh.h"
28
29#if HAVE_LANGINFO_CODESET
30#include <langinfo.h>
31#endif
32#if HAVE_SETLOCALE_CTYPE
33#include <locale.h>
34#endif
35
36__RCSID("$MirOS: src/bin/mksh/main.c,v 1.167 2010/07/04 17:45:15 tg Exp $");
37
38extern char **environ;
39
40#if !HAVE_SETRESUGID
41extern uid_t kshuid;
42extern gid_t kshgid, kshegid;
43#endif
44
45#ifndef MKSHRC_PATH
46#define MKSHRC_PATH "~/.mkshrc"
47#endif
48
49#ifndef MKSH_DEFAULT_TMPDIR
50#define MKSH_DEFAULT_TMPDIR "/tmp"
51#endif
52
53static void reclaim(void);
54static void remove_temps(struct temp *);
55void chvt_reinit(void);
56Source *mksh_init(int, const char *[]);
57#ifdef SIGWINCH
58static void x_sigwinch(int);
59#endif
60
61static const char initifs[] = "IFS= \t\n";
62
63static const char initsubs[] =
64 "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0}";
65
66static const char *initcoms[] = {
67 T_typeset, "-r", initvsn, NULL,
68 T_typeset, "-x", "HOME", "PATH", "RANDOM", "SHELL", NULL,
69 T_typeset, "-i10", "COLUMNS", "LINES", "OPTIND", "PGRP", "PPID",
70 "RANDOM", "SECONDS", "TMOUT", "USER_ID", NULL,
71 "alias",
72 "integer=typeset -i",
73 T_local_typeset,
74 "hash=alias -t", /* not "alias -t --": hash -r needs to work */
75 "type=whence -v",
76#ifndef MKSH_UNEMPLOYED
77 "stop=kill -STOP",
78 "suspend=kill -STOP $$",
79#endif
80 "autoload=typeset -fu",
81 "functions=typeset -f",
82 "history=fc -l",
83 "nameref=typeset -n",
84 "nohup=nohup ",
85 r_fc_e_,
86 "source=PATH=$PATH:. command .",
87 "login=exec login",
88 NULL,
89 /* this is what AT&T ksh seems to track, with the addition of emacs */
90 "alias", "-tU",
91 "cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
92 "make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
93 NULL
94};
95
96static int initio_done;
97
98struct env *e = &kshstate_v.env_;
99
100void
101chvt_reinit(void)
102{
103 kshpid = procpid = getpid();
104 ksheuid = geteuid();
105 kshpgrp = getpgrp();
106 kshppid = getppid();
107}
108
109Source *
110mksh_init(int argc, const char *argv[])
111{
112 int argi, i;
113 Source *s;
114 struct block *l;
115 unsigned char restricted, errexit, utf_flag;
116 const char **wp;
117 struct tbl *vp;
118 struct stat s_stdin;
119#if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
120 size_t k;
121 char *cp;
122#endif
123
124 /* do things like getpgrp() et al. */
125 chvt_reinit();
126
127 /* make sure argv[] is sane */
128 if (!*argv) {
129 static const char *empty_argv[] = {
130 "mksh", NULL
131 };
132
133 argv = empty_argv;
134 argc = 1;
135 }
136 kshname = *argv;
137
138 ainit(&aperm); /* initialise permanent Area */
139
140 /* set up base environment */
141 kshstate_v.env_.type = E_NONE;
142 ainit(&kshstate_v.env_.area);
143 newblock(); /* set up global l->vars and l->funs */
144
145 /* Do this first so output routines (eg, errorf, shellf) can work */
146 initio();
147
148 argi = parse_args(argv, OF_FIRSTTIME, NULL);
149 if (argi < 0)
150 return (NULL);
151
152 initvar();
153
154 initctypes();
155
156 inittraps();
157
158 coproc_init();
159
160 /* set up variable and command dictionaries */
161 ktinit(&taliases, APERM, 0);
162 ktinit(&aliases, APERM, 0);
163#ifndef MKSH_NOPWNAM
164 ktinit(&homedirs, APERM, 0);
165#endif
166
167 /* define shell keywords */
168 initkeywords();
169
170 /* define built-in commands */
171 ktinit(&builtins, APERM,
172 /* must be 80% of 2^n (currently 44 builtins) */ 64);
173 for (i = 0; mkshbuiltins[i].name != NULL; i++)
174 builtin(mkshbuiltins[i].name, mkshbuiltins[i].func);
175
176 init_histvec();
177
178#ifdef _PATH_DEFPATH
179 def_path = _PATH_DEFPATH;
180#else
181#ifdef _CS_PATH
182 if ((k = confstr(_CS_PATH, NULL, 0)) != (size_t)-1 && k > 0 &&
183 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
184 def_path = cp;
185 else
186#endif
187 /*
188 * this is uniform across all OSes unless it
189 * breaks somewhere; don't try to optimise,
190 * e.g. add stuff for Interix or remove /usr
191 * for HURD, because e.g. Debian GNU/HURD is
192 * "keeping a regular /usr"; this is supposed
193 * to be a sane 'basic' default PATH
194 */
195 def_path = "/bin:/usr/bin:/sbin:/usr/sbin";
196#endif
197
198 /* Set PATH to def_path (will set the path global variable).
199 * (import of environment below will probably change this setting).
200 */
201 vp = global("PATH");
202 /* setstr can't fail here */
203 setstr(vp, def_path, KSH_RETURN_ERROR);
204
205 /* Turn on nohup by default for now - will change to off
206 * by default once people are aware of its existence
207 * (AT&T ksh does not have a nohup option - it always sends
208 * the hup).
209 */
210 Flag(FNOHUP) = 1;
211
212 /* Turn on brace expansion by default. AT&T kshs that have
213 * alternation always have it on.
214 */
215 Flag(FBRACEEXPAND) = 1;
216
217 /* Set edit mode to emacs by default, may be overridden
218 * by the environment or the user. Also, we want tab completion
219 * on in vi by default. */
220 change_flag(FEMACS, OF_SPECIAL, 1);
221#if !MKSH_S_NOVI
222 Flag(FVITABCOMPLETE) = 1;
223#endif
224
225#ifdef MKSH_BINSHREDUCED
226 /* set FSH if we're called as -sh or /bin/sh or so */
227 {
228 const char *cc;
229
230 cc = kshname;
231 i = 0; argi = 0;
232 while (cc[i] != '\0')
233 /* the following line matches '-' and '/' ;-) */
234 if ((cc[i++] | 2) == '/')
235 argi = i;
236 if (((cc[argi] | 0x20) == 's') && ((cc[argi + 1] | 0x20) == 'h'))
237 change_flag(FSH, OF_FIRSTTIME, 1);
238 }
239#endif
240
241 /* import environment */
242 if (environ != NULL)
243 for (wp = (const char **)environ; *wp != NULL; wp++)
244 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
245
246 typeset(initifs, 0, 0, 0, 0); /* for security */
247
248 /* assign default shell variable values */
249 substitute(initsubs, 0);
250
251 /* Figure out the current working directory and set $PWD */
252 {
253 struct stat s_pwd, s_dot;
254 struct tbl *pwd_v = global("PWD");
255 char *pwd = str_val(pwd_v);
256 char *pwdx = pwd;
257
258 /* Try to use existing $PWD if it is valid */
259 if (pwd[0] != '/' ||
260 stat(pwd, &s_pwd) < 0 || stat(".", &s_dot) < 0 ||
261 s_pwd.st_dev != s_dot.st_dev ||
262 s_pwd.st_ino != s_dot.st_ino)
263 pwdx = NULL;
264 set_current_wd(pwdx);
265 if (current_wd[0])
266 simplify_path(current_wd);
267 /* Only set pwd if we know where we are or if it had a
268 * bogus value
269 */
270 if (current_wd[0] || pwd != null)
271 /* setstr can't fail here */
272 setstr(pwd_v, current_wd, KSH_RETURN_ERROR);
273 }
274
275 for (wp = initcoms; *wp != NULL; wp++) {
276 shcomexec(wp);
277 while (*wp != NULL)
278 wp++;
279 }
280 setint(global("COLUMNS"), 0);
281 setint(global("LINES"), 0);
282 setint(global("OPTIND"), 1);
283
284 safe_prompt = ksheuid ? "$ " : "# ";
285 vp = global("PS1");
286 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
287 if (!(vp->flag & ISSET) ||
288 (!ksheuid && !strchr(str_val(vp), '#')))
289 /* setstr can't fail here */
290 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
291 setint((vp = global("PGRP")), (mksh_uari_t)kshpgrp);
292 vp->flag |= INT_U;
293 setint((vp = global("PPID")), (mksh_uari_t)kshppid);
294 vp->flag |= INT_U;
295 setint((vp = global("RANDOM")), (mksh_uari_t)evilhash(kshname));
296 vp->flag |= INT_U;
297 setint((vp = global("USER_ID")), (mksh_uari_t)ksheuid);
298 vp->flag |= INT_U;
299
300 /* Set this before parsing arguments */
301#if HAVE_SETRESUGID
302 Flag(FPRIVILEGED) = getuid() != ksheuid || getgid() != getegid();
303#else
304 Flag(FPRIVILEGED) = (kshuid = getuid()) != ksheuid ||
305 (kshgid = getgid()) != (kshegid = getegid());
306#endif
307
308 /* this to note if monitor is set on command line (see below) */
309#ifndef MKSH_UNEMPLOYED
310 Flag(FMONITOR) = 127;
311#endif
312 /* this to note if utf-8 mode is set on command line (see below) */
313 UTFMODE = 2;
314
315 argi = parse_args(argv, OF_CMDLINE, NULL);
316 if (argi < 0)
317 return (NULL);
318
319 /* process this later only, default to off (hysterical raisins) */
320 utf_flag = UTFMODE;
321 UTFMODE = 0;
322
323 if (Flag(FCOMMAND)) {
324 s = pushs(SSTRING, ATEMP);
325 if (!(s->start = s->str = argv[argi++]))
326 errorf("-c requires an argument");
327#ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
328 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
329 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
330 ++argi;
331#endif
332 if (argv[argi])
333 kshname = argv[argi++];
334 } else if (argi < argc && !Flag(FSTDIN)) {
335 s = pushs(SFILE, ATEMP);
336 s->file = argv[argi++];
337 s->u.shf = shf_open(s->file, O_RDONLY, 0,
338 SHF_MAPHI | SHF_CLEXEC);
339 if (s->u.shf == NULL) {
340 shl_stdout_ok = 0;
341 warningf(true, "%s: %s", s->file, strerror(errno));
342 /* mandated by SUSv4 */
343 exstat = 127;
344 unwind(LERROR);
345 }
346 kshname = s->file;
347 } else {
348 Flag(FSTDIN) = 1;
349 s = pushs(SSTDIN, ATEMP);
350 s->file = "<stdin>";
351 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
352 NULL);
353 if (isatty(0) && isatty(2)) {
354 Flag(FTALKING) = Flag(FTALKING_I) = 1;
355 /* The following only if isatty(0) */
356 s->flags |= SF_TTY;
357 s->u.shf->flags |= SHF_INTERRUPT;
358 s->file = NULL;
359 }
360 }
361
362 /* this bizarreness is mandated by POSIX */
363 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
364 Flag(FTALKING))
365 reset_nonblock(0);
366
367 /* initialise job control */
368 j_init();
369 /* set: 0/1; unset: 2->0 */
370 UTFMODE = utf_flag & 1;
371 /* Do this after j_init(), as tty_fd is not initialised until then */
372 if (Flag(FTALKING)) {
373 if (utf_flag == 2) {
374#ifndef MKSH_ASSUME_UTF8
375#define isuc(x) (((x) != NULL) && \
376 (stristr((x), "UTF-8") || stristr((x), "utf8")))
377 /* Check if we're in a UTF-8 locale */
378 const char *ccp;
379
380#if HAVE_SETLOCALE_CTYPE
381 ccp = setlocale(LC_CTYPE, "");
382#if HAVE_LANGINFO_CODESET
383 if (!isuc(ccp))
384 ccp = nl_langinfo(CODESET);
385#endif
386#else
387 /* these were imported from environ earlier */
388 ccp = str_val(global("LC_ALL"));
389 if (ccp == null)
390 ccp = str_val(global("LC_CTYPE"));
391 if (ccp == null)
392 ccp = str_val(global("LANG"));
393#endif
394 UTFMODE = isuc(ccp);
395#undef isuc
396#elif MKSH_ASSUME_UTF8
397 UTFMODE = 1;
398#else
399 UTFMODE = 0;
400#endif
401 }
402 x_init();
403 }
404
405#ifdef SIGWINCH
406 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
407 setsig(&sigtraps[SIGWINCH], x_sigwinch,
408 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
409#endif
410
411 l = e->loc;
412 l->argv = &argv[argi - 1];
413 l->argc = argc - argi;
414 l->argv[0] = kshname;
415 getopts_reset(1);
416
417 /* Disable during .profile/ENV reading */
418 restricted = Flag(FRESTRICTED);
419 Flag(FRESTRICTED) = 0;
420 errexit = Flag(FERREXIT);
421 Flag(FERREXIT) = 0;
422
423 /* Do this before profile/$ENV so that if it causes problems in them,
424 * user will know why things broke.
425 */
426 if (!current_wd[0] && Flag(FTALKING))
427 warningf(false, "Cannot determine current working directory");
428
429 if (Flag(FLOGIN)) {
430 include(KSH_SYSTEM_PROFILE, 0, NULL, 1);
431 if (!Flag(FPRIVILEGED))
432 include(substitute("$HOME/.profile", 0), 0,
433 NULL, 1);
434 }
435 if (Flag(FPRIVILEGED))
436 include("/etc/suid_profile", 0, NULL, 1);
437 else if (Flag(FTALKING)) {
438 char *env_file;
439
440 /* include $ENV */
441 env_file = substitute(substitute("${ENV:-" MKSHRC_PATH "}", 0),
442 DOTILDE);
443 if (*env_file != '\0')
444 include(env_file, 0, NULL, 1);
445 }
446
447 if (restricted) {
448 static const char *restr_com[] = {
449 T_typeset, "-r", "PATH",
450 "ENV", "SHELL",
451 NULL
452 };
453 shcomexec(restr_com);
454 /* After typeset command... */
455 Flag(FRESTRICTED) = 1;
456 }
457 Flag(FERREXIT) = errexit;
458
459 if (Flag(FTALKING)) {
460 hist_init(s);
461 alarm_init();
462 } else
463 Flag(FTRACKALL) = 1; /* set after ENV */
464
465 return (s);
466}
467
468int
469main(int argc, const char *argv[])
470{
471 Source *s;
472
473 kshstate_v.lcg_state_ = 5381;
474
475 if ((s = mksh_init(argc, argv))) {
476 /* put more entropy into the LCG */
477 change_random(s, sizeof(*s));
478 /* doesn’t return */
479 shell(s, true);
480 }
481 return (1);
482}
483
484int
485include(const char *name, int argc, const char **argv, int intr_ok)
486{
487 Source *volatile s = NULL;
488 struct shf *shf;
489 const char **volatile old_argv;
490 volatile int old_argc;
491 int i;
492
493 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
494 if (shf == NULL)
495 return (-1);
496
497 if (argv) {
498 old_argv = e->loc->argv;
499 old_argc = e->loc->argc;
500 } else {
501 old_argv = NULL;
502 old_argc = 0;
503 }
504 newenv(E_INCL);
505 i = sigsetjmp(e->jbuf, 0);
506 if (i) {
507 quitenv(s ? s->u.shf : NULL);
508 if (old_argv) {
509 e->loc->argv = old_argv;
510 e->loc->argc = old_argc;
511 }
512 switch (i) {
513 case LRETURN:
514 case LERROR:
515 return (exstat & 0xff); /* see below */
516 case LINTR:
517 /* intr_ok is set if we are including .profile or $ENV.
518 * If user ^Cs out, we don't want to kill the shell...
519 */
520 if (intr_ok && (exstat - 128) != SIGTERM)
521 return (1);
522 /* FALLTHROUGH */
523 case LEXIT:
524 case LLEAVE:
525 case LSHELL:
526 unwind(i);
527 /* NOTREACHED */
528 default:
529 internal_errorf("include: %d", i);
530 /* NOTREACHED */
531 }
532 }
533 if (argv) {
534 e->loc->argv = argv;
535 e->loc->argc = argc;
536 }
537 s = pushs(SFILE, ATEMP);
538 s->u.shf = shf;
539 strdupx(s->file, name, ATEMP);
540 i = shell(s, false);
541 quitenv(s->u.shf);
542 if (old_argv) {
543 e->loc->argv = old_argv;
544 e->loc->argc = old_argc;
545 }
546 return (i & 0xff); /* & 0xff to ensure value not -1 */
547}
548
549/* spawn a command into a shell optionally keeping track of the line number */
550int
551command(const char *comm, int line)
552{
553 Source *s;
554
555 s = pushs(SSTRING, ATEMP);
556 s->start = s->str = comm;
557 s->line = line;
558 return (shell(s, false));
559}
560
561/*
562 * run the commands from the input source, returning status.
563 */
564int
565shell(Source * volatile s, volatile int toplevel)
566{
567 struct op *t;
568 volatile int wastty = s->flags & SF_TTY;
569 volatile int attempts = 13;
570 volatile int interactive = Flag(FTALKING) && toplevel;
571 Source *volatile old_source = source;
572 int i;
573
574 s->flags |= SF_FIRST; /* enable UTF-8 BOM check */
575
576 newenv(E_PARSE);
577 if (interactive)
578 really_exit = 0;
579 i = sigsetjmp(e->jbuf, 0);
580 if (i) {
581 switch (i) {
582 case LINTR: /* we get here if SIGINT not caught or ignored */
583 case LERROR:
584 case LSHELL:
585 if (interactive) {
586 if (i == LINTR)
587 shellf("\n");
588 /* Reset any eof that was read as part of a
589 * multiline command.
590 */
591 if (Flag(FIGNOREEOF) && s->type == SEOF &&
592 wastty)
593 s->type = SSTDIN;
594 /* Used by exit command to get back to
595 * top level shell. Kind of strange since
596 * interactive is set if we are reading from
597 * a tty, but to have stopped jobs, one only
598 * needs FMONITOR set (not FTALKING/SF_TTY)...
599 */
600 /* toss any input we have so far */
601 s->start = s->str = null;
602 break;
603 }
604 /* FALLTHROUGH */
605 case LEXIT:
606 case LLEAVE:
607 case LRETURN:
608 source = old_source;
609 quitenv(NULL);
610 unwind(i); /* keep on going */
611 /* NOTREACHED */
612 default:
613 source = old_source;
614 quitenv(NULL);
615 internal_errorf("shell: %d", i);
616 /* NOTREACHED */
617 }
618 }
619 while (1) {
620 if (trap)
621 runtraps(0);
622
623 if (s->next == NULL) {
624 if (Flag(FVERBOSE))
625 s->flags |= SF_ECHO;
626 else
627 s->flags &= ~SF_ECHO;
628 }
629 if (interactive) {
630 j_notify();
631 set_prompt(PS1, s);
632 }
633 t = compile(s);
634 if (t != NULL && t->type == TEOF) {
635 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
636 shellf("Use 'exit' to leave ksh\n");
637 s->type = SSTDIN;
638 } else if (wastty && !really_exit &&
639 j_stopped_running()) {
640 really_exit = 1;
641 s->type = SSTDIN;
642 } else {
643 /* this for POSIX which says EXIT traps
644 * shall be taken in the environment
645 * immediately after the last command
646 * executed.
647 */
648 if (toplevel)
649 unwind(LEXIT);
650 break;
651 }
652 }
653 if (t && (!Flag(FNOEXEC) || (s->flags & SF_TTY)))
654 exstat = execute(t, 0, NULL);
655
656 if (t != NULL && t->type != TEOF && interactive && really_exit)
657 really_exit = 0;
658
659 reclaim();
660 }
661 quitenv(NULL);
662 source = old_source;
663 return (exstat);
664}
665
666/* return to closest error handler or shell(), exit if none found */
667void
668unwind(int i)
669{
670 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
671 if (i == LEXIT || (Flag(FERREXIT) && (i == LERROR || i == LINTR) &&
672 sigtraps[SIGEXIT_].trap)) {
673 runtrap(&sigtraps[SIGEXIT_]);
674 i = LLEAVE;
675 } else if (Flag(FERREXIT) && (i == LERROR || i == LINTR)) {
676 runtrap(&sigtraps[SIGERR_]);
677 i = LLEAVE;
678 }
679 while (1) {
680 switch (e->type) {
681 case E_PARSE:
682 case E_FUNC:
683 case E_INCL:
684 case E_LOOP:
685 case E_ERRH:
686 siglongjmp(e->jbuf, i);
687 /* NOTREACHED */
688 case E_NONE:
689 if (i == LINTR)
690 e->flags |= EF_FAKE_SIGDIE;
691 /* FALLTHROUGH */
692 default:
693 quitenv(NULL);
694 }
695 }
696}
697
698void
699newenv(int type)
700{
701 struct env *ep;
702 char *cp;
703
704 /*
705 * struct env includes ALLOC_ITEM for alignment constraints
706 * so first get the actually used memory, then assign it
707 */
708 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
709 ep = (void *)(cp - ALLOC_SIZE); /* undo what alloc() did */
710 /* initialise public members of struct env (not the ALLOC_ITEM) */
711 ainit(&ep->area);
712 ep->oenv = e;
713 ep->loc = e->loc;
714 ep->savefd = NULL;
715 ep->temps = NULL;
716 ep->type = type;
717 ep->flags = 0;
718 /* jump buffer is invalid because flags == 0 */
719 e = ep;
720}
721
722void
723quitenv(struct shf *shf)
724{
725 struct env *ep = e;
726 char *cp;
727 int fd;
728
729 if (ep->oenv && ep->oenv->loc != ep->loc)
730 popblock();
731 if (ep->savefd != NULL) {
732 for (fd = 0; fd < NUFILE; fd++)
733 /* if ep->savefd[fd] < 0, means fd was closed */
734 if (ep->savefd[fd])
735 restfd(fd, ep->savefd[fd]);
736 if (ep->savefd[2]) /* Clear any write errors */
737 shf_reopen(2, SHF_WR, shl_out);
738 }
739 /* Bottom of the stack.
740 * Either main shell is exiting or cleanup_parents_env() was called.
741 */
742 if (ep->oenv == NULL) {
743 if (ep->type == E_NONE) { /* Main shell exiting? */
744#if HAVE_PERSISTENT_HISTORY
745 if (Flag(FTALKING))
746 hist_finish();
747#endif
748 j_exit();
749 if (ep->flags & EF_FAKE_SIGDIE) {
750 int sig = exstat - 128;
751
752 /* ham up our death a bit (AT&T ksh
753 * only seems to do this for SIGTERM)
754 * Don't do it for SIGQUIT, since we'd
755 * dump a core..
756 */
757 if ((sig == SIGINT || sig == SIGTERM) &&
758 (kshpgrp == kshpid)) {
759 setsig(&sigtraps[sig], SIG_DFL,
760 SS_RESTORE_CURR | SS_FORCE);
761 kill(0, sig);
762 }
763 }
764 }
765 if (shf)
766 shf_close(shf);
767 reclaim();
768 exit(exstat);
769 }
770 if (shf)
771 shf_close(shf);
772 reclaim();
773
774 e = e->oenv;
775
776 /* free the struct env - tricky due to the ALLOC_ITEM inside */
777 cp = (void *)ep;
778 afree(cp + ALLOC_SIZE, ATEMP);
779}
780
781/* Called after a fork to cleanup stuff left over from parents environment */
782void
783cleanup_parents_env(void)
784{
785 struct env *ep;
786 int fd;
787
788 mkssert(e != NULL);
789
790 /*
791 * Don't clean up temporary files - parent will probably need them.
792 * Also, can't easily reclaim memory since variables, etc. could be
793 * anywhere.
794 */
795
796 /* close all file descriptors hiding in savefd */
797 for (ep = e; ep; ep = ep->oenv) {
798 if (ep->savefd) {
799 for (fd = 0; fd < NUFILE; fd++)
800 if (ep->savefd[fd] > 0)
801 close(ep->savefd[fd]);
802 afree(ep->savefd, &ep->area);
803 ep->savefd = NULL;
804 }
805 }
806 e->oenv = NULL;
807}
808
809/* Called just before an execve cleanup stuff temporary files */
810void
811cleanup_proc_env(void)
812{
813 struct env *ep;
814
815 for (ep = e; ep; ep = ep->oenv)
816 remove_temps(ep->temps);
817}
818
819/* remove temp files and free ATEMP Area */
820static void
821reclaim(void)
822{
823 remove_temps(e->temps);
824 e->temps = NULL;
825 afreeall(&e->area);
826}
827
828static void
829remove_temps(struct temp *tp)
830{
831 for (; tp != NULL; tp = tp->next)
832 if (tp->pid == procpid)
833 unlink(tp->name);
834}
835
836/* Initialise tty_fd. Used for saving/reseting tty modes upon
837 * foreground job completion and for setting up tty process group.
838 */
839void
840tty_init(bool init_ttystate, bool need_tty)
841{
842 bool do_close = true;
843 int tfd;
844
845 if (tty_fd >= 0) {
846 close(tty_fd);
847 tty_fd = -1;
848 }
849 tty_devtty = 1;
850
851#ifdef _UWIN
852 /* XXX imake style */
853 if (isatty(3))
854 tfd = 3;
855 else
856#endif
857 if ((tfd = open("/dev/tty", O_RDWR, 0)) < 0) {
858 tty_devtty = 0;
859 if (need_tty)
860 warningf(false,
861 "No controlling tty (open /dev/tty: %s)",
862 strerror(errno));
863 }
864 if (tfd < 0) {
865 do_close = false;
866 if (isatty(0))
867 tfd = 0;
868 else if (isatty(2))
869 tfd = 2;
870 else {
871 if (need_tty)
872 warningf(false,
873 "Can't find tty file descriptor");
874 return;
875 }
876 }
877 if ((tty_fd = fcntl(tfd, F_DUPFD, FDBASE)) < 0) {
878 if (need_tty)
879 warningf(false, "j_ttyinit: dup of tty fd failed: %s",
880 strerror(errno));
881 } else if (fcntl(tty_fd, F_SETFD, FD_CLOEXEC) < 0) {
882 if (need_tty)
883 warningf(false,
884 "j_ttyinit: can't set close-on-exec flag: %s",
885 strerror(errno));
886 close(tty_fd);
887 tty_fd = -1;
888 } else if (init_ttystate)
889 tcgetattr(tty_fd, &tty_state);
890 if (do_close)
891 close(tfd);
892}
893
894void
895tty_close(void)
896{
897 if (tty_fd >= 0) {
898 close(tty_fd);
899 tty_fd = -1;
900 }
901}
902
903/* A shell error occurred (eg, syntax error, etc.) */
904void
905errorf(const char *fmt, ...)
906{
907 va_list va;
908
909 shl_stdout_ok = 0; /* debugging: note that stdout not valid */
910 exstat = 1;
911 if (*fmt != 1) {
912 error_prefix(true);
913 va_start(va, fmt);
914 shf_vfprintf(shl_out, fmt, va);
915 va_end(va);
916 shf_putchar('\n', shl_out);
917 }
918 shf_flush(shl_out);
919 unwind(LERROR);
920}
921
922/* like errorf(), but no unwind is done */
923void
924warningf(bool fileline, const char *fmt, ...)
925{
926 va_list va;
927
928 error_prefix(fileline);
929 va_start(va, fmt);
930 shf_vfprintf(shl_out, fmt, va);
931 va_end(va);
932 shf_putchar('\n', shl_out);
933 shf_flush(shl_out);
934}
935
936/* Used by built-in utilities to prefix shell and utility name to message
937 * (also unwinds environments for special builtins).
938 */
939void
940bi_errorf(const char *fmt, ...)
941{
942 va_list va;
943
944 shl_stdout_ok = 0; /* debugging: note that stdout not valid */
945 exstat = 1;
946 if (*fmt != 1) {
947 error_prefix(true);
948 /* not set when main() calls parse_args() */
949 if (builtin_argv0)
950 shf_fprintf(shl_out, "%s: ", builtin_argv0);
951 va_start(va, fmt);
952 shf_vfprintf(shl_out, fmt, va);
953 va_end(va);
954 shf_putchar('\n', shl_out);
955 }
956 shf_flush(shl_out);
957 /* POSIX special builtins and ksh special builtins cause
958 * non-interactive shells to exit.
959 * XXX odd use of KEEPASN; also may not want LERROR here
960 */
961 if (builtin_flag & SPEC_BI) {
962 builtin_argv0 = NULL;
963 unwind(LERROR);
964 }
965}
966
967/* Called when something that shouldn't happen does */
968void
969internal_verrorf(const char *fmt, va_list ap)
970{
971 shf_fprintf(shl_out, "internal error: ");
972 shf_vfprintf(shl_out, fmt, ap);
973 shf_putchar('\n', shl_out);
974 shf_flush(shl_out);
975}
976
977void
978internal_errorf(const char *fmt, ...)
979{
980 va_list va;
981
982 va_start(va, fmt);
983 internal_verrorf(fmt, va);
984 va_end(va);
985 unwind(LERROR);
986}
987
988void
989internal_warningf(const char *fmt, ...)
990{
991 va_list va;
992
993 va_start(va, fmt);
994 internal_verrorf(fmt, va);
995 va_end(va);
996}
997
998/* used by error reporting functions to print "ksh: .kshrc[25]: " */
999void
1000error_prefix(bool fileline)
1001{
1002 /* Avoid foo: foo[2]: ... */
1003 if (!fileline || !source || !source->file ||
1004 strcmp(source->file, kshname) != 0)
1005 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1006 if (fileline && source && source->file != NULL) {
1007 shf_fprintf(shl_out, "%s[%d]: ", source->file,
1008 source->errline > 0 ? source->errline : source->line);
1009 source->errline = 0;
1010 }
1011}
1012
1013/* printf to shl_out (stderr) with flush */
1014void
1015shellf(const char *fmt, ...)
1016{
1017 va_list va;
1018
1019 if (!initio_done) /* shl_out may not be set up yet... */
1020 return;
1021 va_start(va, fmt);
1022 shf_vfprintf(shl_out, fmt, va);
1023 va_end(va);
1024 shf_flush(shl_out);
1025}
1026
1027/* printf to shl_stdout (stdout) */
1028void
1029shprintf(const char *fmt, ...)
1030{
1031 va_list va;
1032
1033 if (!shl_stdout_ok)
1034 internal_errorf("shl_stdout not valid");
1035 va_start(va, fmt);
1036 shf_vfprintf(shl_stdout, fmt, va);
1037 va_end(va);
1038}
1039
1040/* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1041int
1042can_seek(int fd)
1043{
1044 struct stat statb;
1045
1046 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1047 SHF_UNBUF : 0);
1048}
1049
1050struct shf shf_iob[3];
1051
1052void
1053initio(void)
1054{
1055 shf_fdopen(1, SHF_WR, shl_stdout); /* force buffer allocation */
1056 shf_fdopen(2, SHF_WR, shl_out);
1057 shf_fdopen(2, SHF_WR, shl_spare); /* force buffer allocation */
1058 initio_done = 1;
1059}
1060
1061/* A dup2() with error checking */
1062int
1063ksh_dup2(int ofd, int nfd, bool errok)
1064{
1065 int rv;
1066
1067 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1068 errorf("too many files open in shell");
1069
1070#ifdef __ultrix
1071 /* XXX imake style */
1072 if (rv >= 0)
1073 fcntl(nfd, F_SETFD, 0);
1074#endif
1075
1076 return (rv);
1077}
1078
1079/*
1080 * move fd from user space (0<=fd<10) to shell space (fd>=10),
1081 * set close-on-exec flag.
1082 */
1083short
1084savefd(int fd)
1085{
1086 int nfd = fd;
1087
1088 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1089 errno == EBADF)
1090 return (-1);
1091 if (nfd < 0 || nfd > SHRT_MAX)
1092 errorf("too many files open in shell");
1093 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1094 return ((short)nfd);
1095}
1096
1097void
1098restfd(int fd, int ofd)
1099{
1100 if (fd == 2)
1101 shf_flush(&shf_iob[fd]);
1102 if (ofd < 0) /* original fd closed */
1103 close(fd);
1104 else if (fd != ofd) {
1105 ksh_dup2(ofd, fd, true); /* XXX: what to do if this fails? */
1106 close(ofd);
1107 }
1108}
1109
1110void
1111openpipe(int *pv)
1112{
1113 int lpv[2];
1114
1115 if (pipe(lpv) < 0)
1116 errorf("can't create pipe - try again");
1117 pv[0] = savefd(lpv[0]);
1118 if (pv[0] != lpv[0])
1119 close(lpv[0]);
1120 pv[1] = savefd(lpv[1]);
1121 if (pv[1] != lpv[1])
1122 close(lpv[1]);
1123}
1124
1125void
1126closepipe(int *pv)
1127{
1128 close(pv[0]);
1129 close(pv[1]);
1130}
1131
1132/* Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1133 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1134 */
1135int
1136check_fd(const char *name, int mode, const char **emsgp)
1137{
1138 int fd, fl;
1139
1140 if (name[0] == 'p' && !name[1])
1141 return (coproc_getfd(mode, emsgp));
1142 for (fd = 0; ksh_isdigit(*name); ++name)
1143 fd = (fd * 10) + *name - '0';
1144 if (*name || fd >= FDBASE) {
1145 if (emsgp)
1146 *emsgp = "illegal file descriptor name";
1147 return (-1);
1148 }
1149 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1150 if (emsgp)
1151 *emsgp = "bad file descriptor";
1152 return (-1);
1153 }
1154 fl &= O_ACCMODE;
1155 /* X_OK is a kludge to disable this check for dups (x<&1):
1156 * historical shells never did this check (XXX don't know what
1157 * POSIX has to say).
1158 */
1159 if (!(mode & X_OK) && fl != O_RDWR && (
1160 ((mode & R_OK) && fl != O_RDONLY) ||
1161 ((mode & W_OK) && fl != O_WRONLY))) {
1162 if (emsgp)
1163 *emsgp = (fl == O_WRONLY) ?
1164 "fd not open for reading" :
1165 "fd not open for writing";
1166 return (-1);
1167 }
1168 return (fd);
1169}
1170
1171/* Called once from main */
1172void
1173coproc_init(void)
1174{
1175 coproc.read = coproc.readw = coproc.write = -1;
1176 coproc.njobs = 0;
1177 coproc.id = 0;
1178}
1179
1180/* Called by c_read() when eof is read - close fd if it is the co-process fd */
1181void
1182coproc_read_close(int fd)
1183{
1184 if (coproc.read >= 0 && fd == coproc.read) {
1185 coproc_readw_close(fd);
1186 close(coproc.read);
1187 coproc.read = -1;
1188 }
1189}
1190
1191/* Called by c_read() and by iosetup() to close the other side of the
1192 * read pipe, so reads will actually terminate.
1193 */
1194void
1195coproc_readw_close(int fd)
1196{
1197 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1198 close(coproc.readw);
1199 coproc.readw = -1;
1200 }
1201}
1202
1203/* Called by c_print when a write to a fd fails with EPIPE and by iosetup
1204 * when co-process input is dup'd
1205 */
1206void
1207coproc_write_close(int fd)
1208{
1209 if (coproc.write >= 0 && fd == coproc.write) {
1210 close(coproc.write);
1211 coproc.write = -1;
1212 }
1213}
1214
1215/* Called to check for existence of/value of the co-process file descriptor.
1216 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1217 */
1218int
1219coproc_getfd(int mode, const char **emsgp)
1220{
1221 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1222
1223 if (fd >= 0)
1224 return (fd);
1225 if (emsgp)
1226 *emsgp = "no coprocess";
1227 return (-1);
1228}
1229
1230/* called to close file descriptors related to the coprocess (if any)
1231 * Should be called with SIGCHLD blocked.
1232 */
1233void
1234coproc_cleanup(int reuse)
1235{
1236 /* This to allow co-processes to share output pipe */
1237 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1238 if (coproc.read >= 0) {
1239 close(coproc.read);
1240 coproc.read = -1;
1241 }
1242 if (coproc.readw >= 0) {
1243 close(coproc.readw);
1244 coproc.readw = -1;
1245 }
1246 }
1247 if (coproc.write >= 0) {
1248 close(coproc.write);
1249 coproc.write = -1;
1250 }
1251}
1252
1253struct temp *
1254maketemp(Area *ap, Temp_type type, struct temp **tlist)
1255{
1256 struct temp *tp;
1257 int len;
1258 int fd;
1259 char *pathname;
1260 const char *dir;
1261
1262 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1263#if HAVE_MKSTEMP
1264 len = strlen(dir) + 6 + 10 + 1;
1265#else
1266 pathname = tempnam(dir, "mksh.");
1267 len = ((pathname == NULL) ? 0 : strlen(pathname)) + 1;
1268#endif
1269 tp = alloc(sizeof(struct temp) + len, ap);
1270 tp->name = (char *)&tp[1];
1271#if !HAVE_MKSTEMP
1272 if (pathname == NULL)
1273 tp->name[0] = '\0';
1274 else {
1275 memcpy(tp->name, pathname, len);
1276 free(pathname);
1277 }
1278#endif
1279 pathname = tp->name;
1280 tp->shf = NULL;
1281 tp->type = type;
1282#if HAVE_MKSTEMP
1283 shf_snprintf(pathname, len, "%s/mksh.XXXXXXXXXX", dir);
1284 if ((fd = mkstemp(pathname)) >= 0)
1285#else
1286 if (tp->name[0] && (fd = open(tp->name, O_CREAT | O_RDWR, 0600)) >= 0)
1287#endif
1288 tp->shf = shf_fdopen(fd, SHF_WR, NULL);
1289 tp->pid = procpid;
1290
1291 tp->next = *tlist;
1292 *tlist = tp;
1293 return (tp);
1294}
1295
1296/*
1297 * We use a similar collision resolution algorithm as Python 2.5.4
1298 * but with a slightly tweaked implementation written from scratch.
1299 */
1300
1301#define INIT_TBLS 8 /* initial table size (power of 2) */
1302#define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1303
1304static void texpand(struct table *, size_t);
1305static int tnamecmp(const void *, const void *);
1306static struct tbl *ktscan(struct table *, const char *, uint32_t,
1307 struct tbl ***);
1308
1309static void
1310texpand(struct table *tp, size_t nsize)
1311{
1312 size_t i, j, osize = tp->size, perturb;
1313 struct tbl *tblp, **pp;
1314 struct tbl **ntblp, **otblp = tp->tbls;
1315
1316 ntblp = alloc(nsize * sizeof(struct tbl *), tp->areap);
1317 for (i = 0; i < nsize; i++)
1318 ntblp[i] = NULL;
1319 tp->size = nsize;
1320 tp->nfree = (nsize * 4) / 5; /* table can get 80% full */
1321 tp->tbls = ntblp;
1322 if (otblp == NULL)
1323 return;
1324 nsize--; /* from here on nsize := mask */
1325 for (i = 0; i < osize; i++)
1326 if ((tblp = otblp[i]) != NULL) {
1327 if ((tblp->flag & DEFINED)) {
1328 /* search for free hash table slot */
1329 j = (perturb = tblp->ua.hval) & nsize;
1330 goto find_first_empty_slot;
1331 find_next_empty_slot:
1332 j = (j << 2) + j + perturb + 1;
1333 perturb >>= PERTURB_SHIFT;
1334 find_first_empty_slot:
1335 pp = &ntblp[j & nsize];
1336 if (*pp != NULL)
1337 goto find_next_empty_slot;
1338 /* found an empty hash table slot */
1339 *pp = tblp;
1340 tp->nfree--;
1341 } else if (!(tblp->flag & FINUSE)) {
1342 afree(tblp, tp->areap);
1343 }
1344 }
1345 afree(otblp, tp->areap);
1346}
1347
1348void
1349ktinit(struct table *tp, Area *ap, size_t tsize)
1350{
1351 tp->areap = ap;
1352 tp->tbls = NULL;
1353 tp->size = tp->nfree = 0;
1354 if (tsize)
1355 texpand(tp, tsize);
1356}
1357
1358/* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1359static struct tbl *
1360ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1361{
1362 size_t j, perturb, mask;
1363 struct tbl **pp, *p;
1364
1365 mask = tp->size - 1;
1366 /* search for hash table slot matching name */
1367 j = (perturb = h) & mask;
1368 goto find_first_slot;
1369 find_next_slot:
1370 j = (j << 2) + j + perturb + 1;
1371 perturb >>= PERTURB_SHIFT;
1372 find_first_slot:
1373 pp = &tp->tbls[j & mask];
1374 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1375 strcmp(p->name, name)))
1376 goto find_next_slot;
1377 /* p == NULL if not found, correct found entry otherwise */
1378 if (ppp)
1379 *ppp = pp;
1380 return (p);
1381}
1382
1383/* table, name (key) to search for, hash(n) */
1384struct tbl *
1385ktsearch(struct table *tp, const char *n, uint32_t h)
1386{
1387 return (tp->size ? ktscan(tp, n, h, NULL) : NULL);
1388}
1389
1390/* table, name (key) to enter, hash(n) */
1391struct tbl *
1392ktenter(struct table *tp, const char *n, uint32_t h)
1393{
1394 struct tbl **pp, *p;
1395 int len;
1396
1397 if (tp->size == 0)
1398 texpand(tp, INIT_TBLS);
1399 Search:
1400 if ((p = ktscan(tp, n, h, &pp)))
1401 return (p);
1402
1403 if (tp->nfree <= 0) {
1404 /* too full */
1405 texpand(tp, 2 * tp->size);
1406 goto Search;
1407 }
1408
1409 /* create new tbl entry */
1410 len = strlen(n) + 1;
1411 p = alloc(offsetof(struct tbl, name[0]) + len, tp->areap);
1412 p->flag = 0;
1413 p->type = 0;
1414 p->areap = tp->areap;
1415 p->ua.hval = h;
1416 p->u2.field = 0;
1417 p->u.array = NULL;
1418 memcpy(p->name, n, len);
1419
1420 /* enter in tp->tbls */
1421 tp->nfree--;
1422 *pp = p;
1423 return (p);
1424}
1425
1426void
1427ktwalk(struct tstate *ts, struct table *tp)
1428{
1429 ts->left = tp->size;
1430 ts->next = tp->tbls;
1431}
1432
1433struct tbl *
1434ktnext(struct tstate *ts)
1435{
1436 while (--ts->left >= 0) {
1437 struct tbl *p = *ts->next++;
1438 if (p != NULL && (p->flag & DEFINED))
1439 return (p);
1440 }
1441 return (NULL);
1442}
1443
1444static int
1445tnamecmp(const void *p1, const void *p2)
1446{
1447 const struct tbl *a = *((const struct tbl * const *)p1);
1448 const struct tbl *b = *((const struct tbl * const *)p2);
1449
1450 return (strcmp(a->name, b->name));
1451}
1452
1453struct tbl **
1454ktsort(struct table *tp)
1455{
1456 size_t i;
1457 struct tbl **p, **sp, **dp;
1458
1459 p = alloc((tp->size + 1) * sizeof(struct tbl *), ATEMP);
1460 sp = tp->tbls; /* source */
1461 dp = p; /* dest */
1462 i = (size_t)tp->size;
1463 while (i--)
1464 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1465 ((*dp)->flag & ARRAY)))
1466 dp++;
1467 qsort(p, (i = dp - p), sizeof(void *), tnamecmp);
1468 p[i] = NULL;
1469 return (p);
1470}
1471
1472#ifdef SIGWINCH
1473static void
1474x_sigwinch(int sig MKSH_A_UNUSED)
1475{
1476 /* this runs inside interrupt context, with errno saved */
1477
1478 got_winch = 1;
1479}
1480#endif