Home | History | Annotate | Download | only in src
      1 /*	$OpenBSD: main.c,v 1.54 2013/11/28 10:33:37 sobrado Exp $	*/
      2 /*	$OpenBSD: tty.c,v 1.10 2014/08/10 02:44:26 guenther Exp $	*/
      3 /*	$OpenBSD: io.c,v 1.25 2014/08/11 20:28:47 guenther Exp $	*/
      4 /*	$OpenBSD: table.c,v 1.15 2012/02/19 07:52:30 otto Exp $	*/
      5 
      6 /*-
      7  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
      8  *		 2011, 2012, 2013, 2014
      9  *	Thorsten Glaser <tg (at) mirbsd.org>
     10  *
     11  * Provided that these terms and disclaimer and all copyright notices
     12  * are retained or reproduced in an accompanying document, permission
     13  * is granted to deal in this work without restriction, including un-
     14  * limited rights to use, publicly perform, distribute, sell, modify,
     15  * merge, give away, or sublicence.
     16  *
     17  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
     18  * the utmost extent permitted by applicable law, neither express nor
     19  * implied; without malicious intent or gross negligence. In no event
     20  * may a licensor, author or contributor be held liable for indirect,
     21  * direct, other damage, loss, or other issues arising in any way out
     22  * of dealing in the work, even if advised of the possibility of such
     23  * damage or existence of a defect, except proven that it results out
     24  * of said person's immediate fault when using the work as intended.
     25  */
     26 
     27 #define EXTERN
     28 #include "sh.h"
     29 
     30 #if HAVE_LANGINFO_CODESET
     31 #include <langinfo.h>
     32 #endif
     33 #if HAVE_SETLOCALE_CTYPE
     34 #include <locale.h>
     35 #endif
     36 
     37 __RCSID("$MirOS: src/bin/mksh/main.c,v 1.284 2014/10/03 17:19:27 tg Exp $");
     38 
     39 extern char **environ;
     40 
     41 #ifndef MKSHRC_PATH
     42 #define MKSHRC_PATH	"~/.mkshrc"
     43 #endif
     44 
     45 #ifndef MKSH_DEFAULT_TMPDIR
     46 #define MKSH_DEFAULT_TMPDIR	"/tmp"
     47 #endif
     48 
     49 static uint8_t isuc(const char *);
     50 static int main_init(int, const char *[], Source **, struct block **);
     51 void chvt_reinit(void);
     52 static void reclaim(void);
     53 static void remove_temps(struct temp *);
     54 static mksh_uari_t rndsetup(void);
     55 #ifdef SIGWINCH
     56 static void x_sigwinch(int);
     57 #endif
     58 
     59 static const char initifs[] = "IFS= \t\n";
     60 
     61 static const char initsubs[] =
     62     "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0} ${EPOCHREALTIME=}";
     63 
     64 static const char *initcoms[] = {
     65 	Ttypeset, "-r", initvsn, NULL,
     66 	Ttypeset, "-x", "HOME", "PATH", "SHELL", NULL,
     67 	Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
     68 	Talias,
     69 	"integer=typeset -i",
     70 	Tlocal_typeset,
     71 	/* not "alias -t --": hash -r needs to work */
     72 	"hash=alias -t",
     73 	"type=whence -v",
     74 #if !defined(ANDROID) && !defined(MKSH_UNEMPLOYED)
     75 	/* not in Android for political reasons */
     76 	/* not in ARGE mksh due to no job control */
     77 	"stop=kill -STOP",
     78 #endif
     79 	"autoload=typeset -fu",
     80 	"functions=typeset -f",
     81 	"history=fc -l",
     82 	"nameref=typeset -n",
     83 	"nohup=nohup ",
     84 	Tr_fc_e_dash,
     85 	"source=PATH=$PATH:. command .",
     86 	"login=exec login",
     87 	NULL,
     88 	 /* this is what AT&T ksh seems to track, with the addition of emacs */
     89 	Talias, "-tU",
     90 	"cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
     91 	"make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
     92 	NULL
     93 };
     94 
     95 static const char *restr_com[] = {
     96 	Ttypeset, "-r", "PATH", "ENV", "SHELL", NULL
     97 };
     98 
     99 static bool initio_done;
    100 
    101 /* top-level parsing and execution environment */
    102 static struct env env;
    103 struct env *e = &env;
    104 
    105 static mksh_uari_t
    106 rndsetup(void)
    107 {
    108 	register uint32_t h;
    109 	struct {
    110 		ALLOC_ITEM alloc_INT;
    111 		void *dataptr, *stkptr, *mallocptr;
    112 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
    113 		sigjmp_buf jbuf;
    114 #endif
    115 		struct timeval tv;
    116 	} *bufptr;
    117 	char *cp;
    118 
    119 	cp = alloc(sizeof(*bufptr) - ALLOC_SIZE, APERM);
    120 #ifdef DEBUG
    121 	/* clear the allocated space, for valgrind */
    122 	memset(cp, 0, sizeof(*bufptr) - ALLOC_SIZE);
    123 #endif
    124 	/* undo what alloc() did to the malloc result address */
    125 	bufptr = (void *)(cp - ALLOC_SIZE);
    126 	/* PIE or something similar provides us with deltas here */
    127 	bufptr->dataptr = &rndsetupstate;
    128 	/* ASLR in at least Windows, Linux, some BSDs */
    129 	bufptr->stkptr = &bufptr;
    130 	/* randomised malloc in BSD (and possibly others) */
    131 	bufptr->mallocptr = bufptr;
    132 #if defined(__GLIBC__) && (__GLIBC__ >= 2)
    133 	/* glibc pointer guard */
    134 	sigsetjmp(bufptr->jbuf, 1);
    135 #endif
    136 	/* introduce variation (and yes, second arg MBZ for portability) */
    137 	mksh_TIME(bufptr->tv);
    138 
    139 	h = chvt_rndsetup(bufptr, sizeof(*bufptr));
    140 
    141 	afree(cp, APERM);
    142 	return ((mksh_uari_t)h);
    143 }
    144 
    145 void
    146 chvt_reinit(void)
    147 {
    148 	kshpid = procpid = getpid();
    149 	ksheuid = geteuid();
    150 	kshpgrp = getpgrp();
    151 	kshppid = getppid();
    152 }
    153 
    154 static const char *empty_argv[] = {
    155 	"mksh", NULL
    156 };
    157 
    158 static uint8_t
    159 isuc(const char *cx) {
    160 	char *cp, *x;
    161 	uint8_t rv = 0;
    162 
    163 	if (!cx || !*cx)
    164 		return (0);
    165 
    166 	/* uppercase a string duplicate */
    167 	strdupx(x, cx, ATEMP);
    168 	cp = x;
    169 	while ((*cp = ksh_toupper(*cp)))
    170 		++cp;
    171 
    172 	/* check for UTF-8 */
    173 	if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
    174 		rv = 1;
    175 
    176 	/* free copy and out */
    177 	afree(x, ATEMP);
    178 	return (rv);
    179 }
    180 
    181 static int
    182 main_init(int argc, const char *argv[], Source **sp, struct block **lp)
    183 {
    184 	int argi, i;
    185 	Source *s = NULL;
    186 	struct block *l;
    187 	unsigned char restricted_shell, errexit, utf_flag;
    188 	char *cp;
    189 	const char *ccp, **wp;
    190 	struct tbl *vp;
    191 	struct stat s_stdin;
    192 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
    193 	ssize_t k;
    194 #endif
    195 
    196 	/* do things like getpgrp() et al. */
    197 	chvt_reinit();
    198 
    199 	/* make sure argv[] is sane */
    200 	if (!*argv) {
    201 		argv = empty_argv;
    202 		argc = 1;
    203 	}
    204 	kshname = argv[0];
    205 
    206 	/* initialise permanent Area */
    207 	ainit(&aperm);
    208 
    209 	/* set up base environment */
    210 	env.type = E_NONE;
    211 	ainit(&env.area);
    212 	/* set up global l->vars and l->funs */
    213 	newblock();
    214 
    215 	/* Do this first so output routines (eg, errorf, shellf) can work */
    216 	initio();
    217 
    218 	/* determine the basename (without '-' or path) of the executable */
    219 	ccp = kshname;
    220 	goto begin_parse_kshname;
    221 	while ((i = ccp[argi++])) {
    222 		if (i == '/') {
    223 			ccp += argi;
    224  begin_parse_kshname:
    225 			argi = 0;
    226 			if (*ccp == '-')
    227 				++ccp;
    228 		}
    229 	}
    230 	if (!*ccp)
    231 		ccp = empty_argv[0];
    232 
    233 	/*
    234 	 * Turn on nohup by default. (AT&T ksh does not have a nohup
    235 	 * option - it always sends the hup).
    236 	 */
    237 	Flag(FNOHUP) = 1;
    238 
    239 	/*
    240 	 * Turn on brace expansion by default. AT&T kshs that have
    241 	 * alternation always have it on.
    242 	 */
    243 	Flag(FBRACEEXPAND) = 1;
    244 
    245 	/*
    246 	 * Turn on "set -x" inheritance by default.
    247 	 */
    248 	Flag(FXTRACEREC) = 1;
    249 
    250 	/* define built-in commands and see if we were called as one */
    251 	ktinit(APERM, &builtins,
    252 	    /* currently up to 51 builtins: 75% of 128 = 2^7 */
    253 	    7);
    254 	for (i = 0; mkshbuiltins[i].name != NULL; i++)
    255 		if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
    256 		    mkshbuiltins[i].func)))
    257 			Flag(FAS_BUILTIN) = 1;
    258 
    259 	if (!Flag(FAS_BUILTIN)) {
    260 		/* check for -T option early */
    261 		argi = parse_args(argv, OF_FIRSTTIME, NULL);
    262 		if (argi < 0)
    263 			return (1);
    264 
    265 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
    266 		/* are we called as -sh or /bin/sh or so? */
    267 		if (!strcmp(ccp, "sh")) {
    268 			/* either also turns off braceexpand */
    269 #ifdef MKSH_BINSHPOSIX
    270 			/* enable better POSIX conformance */
    271 			change_flag(FPOSIX, OF_FIRSTTIME, true);
    272 #endif
    273 #ifdef MKSH_BINSHREDUCED
    274 			/* enable kludge/compat mode */
    275 			change_flag(FSH, OF_FIRSTTIME, true);
    276 #endif
    277 		}
    278 #endif
    279 	}
    280 
    281 	initvar();
    282 
    283 	initctypes();
    284 
    285 	inittraps();
    286 
    287 	coproc_init();
    288 
    289 	/* set up variable and command dictionaries */
    290 	ktinit(APERM, &taliases, 0);
    291 	ktinit(APERM, &aliases, 0);
    292 #ifndef MKSH_NOPWNAM
    293 	ktinit(APERM, &homedirs, 0);
    294 #endif
    295 
    296 	/* define shell keywords */
    297 	initkeywords();
    298 
    299 	init_histvec();
    300 
    301 	/* initialise tty size before importing environment */
    302 	change_winsz();
    303 
    304 #ifdef _PATH_DEFPATH
    305 	def_path = _PATH_DEFPATH;
    306 #else
    307 #ifdef _CS_PATH
    308 	if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
    309 	    confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
    310 		def_path = cp;
    311 	else
    312 #endif
    313 		/*
    314 		 * this is uniform across all OSes unless it
    315 		 * breaks somewhere; don't try to optimise,
    316 		 * e.g. add stuff for Interix or remove /usr
    317 		 * for HURD, because e.g. Debian GNU/HURD is
    318 		 * "keeping a regular /usr"; this is supposed
    319 		 * to be a sane 'basic' default PATH
    320 		 */
    321 		def_path = "/bin:/usr/bin:/sbin:/usr/sbin";
    322 #endif
    323 
    324 	/*
    325 	 * Set PATH to def_path (will set the path global variable).
    326 	 * (import of environment below will probably change this setting).
    327 	 */
    328 	vp = global("PATH");
    329 	/* setstr can't fail here */
    330 	setstr(vp, def_path, KSH_RETURN_ERROR);
    331 
    332 #ifndef MKSH_NO_CMDLINE_EDITING
    333 	/*
    334 	 * Set edit mode to emacs by default, may be overridden
    335 	 * by the environment or the user. Also, we want tab completion
    336 	 * on in vi by default.
    337 	 */
    338 	change_flag(FEMACS, OF_SPECIAL, true);
    339 #if !MKSH_S_NOVI
    340 	Flag(FVITABCOMPLETE) = 1;
    341 #endif
    342 #endif
    343 
    344 	/* import environment */
    345 	if (environ != NULL) {
    346 		wp = (const char **)environ;
    347 		while (*wp != NULL) {
    348 			rndpush(*wp);
    349 			typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
    350 			++wp;
    351 		}
    352 	}
    353 
    354 	/* for security */
    355 	typeset(initifs, 0, 0, 0, 0);
    356 
    357 	/* assign default shell variable values */
    358 	substitute(initsubs, 0);
    359 
    360 	/* Figure out the current working directory and set $PWD */
    361 	vp = global("PWD");
    362 	cp = str_val(vp);
    363 	/* Try to use existing $PWD if it is valid */
    364 	set_current_wd((cp[0] == '/' && test_eval(NULL, TO_FILEQ, cp, ".",
    365 	    true)) ? cp : NULL);
    366 	if (current_wd[0])
    367 		simplify_path(current_wd);
    368 	/* Only set pwd if we know where we are or if it had a bogus value */
    369 	if (current_wd[0] || *cp)
    370 		/* setstr can't fail here */
    371 		setstr(vp, current_wd, KSH_RETURN_ERROR);
    372 
    373 	for (wp = initcoms; *wp != NULL; wp++) {
    374 		shcomexec(wp);
    375 		while (*wp != NULL)
    376 			wp++;
    377 	}
    378 	setint_n(global("OPTIND"), 1, 10);
    379 
    380 	kshuid = getuid();
    381 	kshgid = getgid();
    382 	kshegid = getegid();
    383 
    384 	safe_prompt = ksheuid ? "$ " : "# ";
    385 	vp = global("PS1");
    386 	/* Set PS1 if unset or we are root and prompt doesn't contain a # */
    387 	if (!(vp->flag & ISSET) ||
    388 	    (!ksheuid && !strchr(str_val(vp), '#')))
    389 		/* setstr can't fail here */
    390 		setstr(vp, safe_prompt, KSH_RETURN_ERROR);
    391 	setint_n((vp = global("BASHPID")), 0, 10);
    392 	vp->flag |= INT_U;
    393 	setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
    394 	vp->flag |= INT_U;
    395 	setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
    396 	vp->flag |= INT_U;
    397 	setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
    398 	vp->flag |= INT_U;
    399 	setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
    400 	vp->flag |= INT_U;
    401 	setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
    402 	vp->flag |= INT_U;
    403 	setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
    404 	vp->flag |= INT_U;
    405 	setint_n((vp = global("RANDOM")), rndsetup(), 10);
    406 	vp->flag |= INT_U;
    407 	setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
    408 
    409 	/* Set this before parsing arguments */
    410 	Flag(FPRIVILEGED) = (
    411 #if HAVE_ISSETUGID
    412 	    issetugid() ||
    413 #endif
    414 	    kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
    415 
    416 	/* this to note if monitor is set on command line (see below) */
    417 #ifndef MKSH_UNEMPLOYED
    418 	Flag(FMONITOR) = 127;
    419 #endif
    420 	/* this to note if utf-8 mode is set on command line (see below) */
    421 	UTFMODE = 2;
    422 
    423 	if (!Flag(FAS_BUILTIN)) {
    424 		argi = parse_args(argv, OF_CMDLINE, NULL);
    425 		if (argi < 0)
    426 			return (1);
    427 	}
    428 
    429 	/* process this later only, default to off (hysterical raisins) */
    430 	utf_flag = UTFMODE;
    431 	UTFMODE = 0;
    432 
    433 	if (Flag(FAS_BUILTIN)) {
    434 		/* auto-detect from environment variables, always */
    435 		utf_flag = 3;
    436 	} else if (Flag(FCOMMAND)) {
    437 		s = pushs(SSTRINGCMDLINE, ATEMP);
    438 		if (!(s->start = s->str = argv[argi++]))
    439 			errorf("%s %s", "-c", "requires an argument");
    440 		while (*s->str) {
    441 			if (*s->str != ' ' && ctype(*s->str, C_QUOTE))
    442 				break;
    443 			s->str++;
    444 		}
    445 		if (!*s->str)
    446 			s->flags |= SF_MAYEXEC;
    447 		s->str = s->start;
    448 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
    449 		/* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
    450 		if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
    451 			++argi;
    452 #endif
    453 		if (argv[argi])
    454 			kshname = argv[argi++];
    455 	} else if (argi < argc && !Flag(FSTDIN)) {
    456 		s = pushs(SFILE, ATEMP);
    457 		s->file = argv[argi++];
    458 		s->u.shf = shf_open(s->file, O_RDONLY, 0,
    459 		    SHF_MAPHI | SHF_CLEXEC);
    460 		if (s->u.shf == NULL) {
    461 			shl_stdout_ok = false;
    462 			warningf(true, "%s: %s", s->file, cstrerror(errno));
    463 			/* mandated by SUSv4 */
    464 			exstat = 127;
    465 			unwind(LERROR);
    466 		}
    467 		kshname = s->file;
    468 	} else {
    469 		Flag(FSTDIN) = 1;
    470 		s = pushs(SSTDIN, ATEMP);
    471 		s->file = "<stdin>";
    472 		s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
    473 		    NULL);
    474 		if (isatty(0) && isatty(2)) {
    475 			Flag(FTALKING) = Flag(FTALKING_I) = 1;
    476 			/* The following only if isatty(0) */
    477 			s->flags |= SF_TTY;
    478 			s->u.shf->flags |= SHF_INTERRUPT;
    479 			s->file = NULL;
    480 		}
    481 	}
    482 
    483 	/* this bizarreness is mandated by POSIX */
    484 	if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
    485 	    Flag(FTALKING))
    486 		reset_nonblock(0);
    487 
    488 	/* initialise job control */
    489 	j_init();
    490 	/* do this after j_init() which calls tty_init_state() */
    491 	if (Flag(FTALKING)) {
    492 		if (utf_flag == 2) {
    493 #ifndef MKSH_ASSUME_UTF8
    494 			/* auto-detect from locale or environment */
    495 			utf_flag = 4;
    496 #else /* this may not be an #elif */
    497 #if MKSH_ASSUME_UTF8
    498 			utf_flag = 1;
    499 #else
    500 			/* always disable UTF-8 (for interactive) */
    501 			utf_flag = 0;
    502 #endif
    503 #endif
    504 		}
    505 #ifndef MKSH_NO_CMDLINE_EDITING
    506 		x_init();
    507 #endif
    508 	}
    509 
    510 #ifdef SIGWINCH
    511 	sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
    512 	setsig(&sigtraps[SIGWINCH], x_sigwinch,
    513 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
    514 #endif
    515 
    516 	l = e->loc;
    517 	if (Flag(FAS_BUILTIN)) {
    518 		l->argc = argc;
    519 		l->argv = argv;
    520 		l->argv[0] = ccp;
    521 	} else {
    522 		l->argc = argc - argi;
    523 		/*
    524 		 * allocate a new array because otherwise, when we modify
    525 		 * it in-place, ps(1) output changes; the meaning of argc
    526 		 * here is slightly different as it excludes kshname, and
    527 		 * we add a trailing NULL sentinel as well
    528 		 */
    529 		l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
    530 		l->argv[0] = kshname;
    531 		memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
    532 		l->argv[l->argc + 1] = NULL;
    533 		getopts_reset(1);
    534 	}
    535 
    536 	/* divine the initial state of the utf8-mode Flag */
    537 	ccp = null;
    538 	switch (utf_flag) {
    539 
    540 	/* auto-detect from locale or environment */
    541 	case 4:
    542 #if HAVE_SETLOCALE_CTYPE
    543 		ccp = setlocale(LC_CTYPE, "");
    544 #if HAVE_LANGINFO_CODESET
    545 		if (!isuc(ccp))
    546 			ccp = nl_langinfo(CODESET);
    547 #endif
    548 		if (!isuc(ccp))
    549 			ccp = null;
    550 		/* FALLTHROUGH */
    551 #endif
    552 
    553 	/* auto-detect from environment */
    554 	case 3:
    555 		/* these were imported from environ earlier */
    556 		if (ccp == null)
    557 			ccp = str_val(global("LC_ALL"));
    558 		if (ccp == null)
    559 			ccp = str_val(global("LC_CTYPE"));
    560 		if (ccp == null)
    561 			ccp = str_val(global("LANG"));
    562 		UTFMODE = isuc(ccp);
    563 		break;
    564 
    565 	/* not set on command line, not FTALKING */
    566 	case 2:
    567 	/* unknown values */
    568 	default:
    569 		utf_flag = 0;
    570 		/* FALLTHROUGH */
    571 
    572 	/* known values */
    573 	case 1:
    574 	case 0:
    575 		UTFMODE = utf_flag;
    576 		break;
    577 	}
    578 
    579 	/* Disable during .profile/ENV reading */
    580 	restricted_shell = Flag(FRESTRICTED);
    581 	Flag(FRESTRICTED) = 0;
    582 	errexit = Flag(FERREXIT);
    583 	Flag(FERREXIT) = 0;
    584 
    585 	/*
    586 	 * Do this before profile/$ENV so that if it causes problems in them,
    587 	 * user will know why things broke.
    588 	 */
    589 	if (!current_wd[0] && Flag(FTALKING))
    590 		warningf(false, "can't determine current directory");
    591 
    592 	if (Flag(FLOGIN))
    593 		include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
    594 	if (!Flag(FPRIVILEGED)) {
    595 		if (Flag(FLOGIN))
    596 			include(substitute("$HOME/.profile", 0), 0, NULL, true);
    597 		if (Flag(FTALKING)) {
    598 			cp = substitute(substitute("${ENV:-" MKSHRC_PATH "}",
    599 			    0), DOTILDE);
    600 			if (cp[0] != '\0')
    601 				include(cp, 0, NULL, true);
    602 		}
    603 	} else {
    604 		include(MKSH_SUID_PROFILE, 0, NULL, true);
    605 		/* turn off -p if not set explicitly */
    606 		if (Flag(FPRIVILEGED) != 1)
    607 			change_flag(FPRIVILEGED, OF_INTERNAL, false);
    608 	}
    609 
    610 	if (restricted_shell) {
    611 		shcomexec(restr_com);
    612 		/* After typeset command... */
    613 		Flag(FRESTRICTED) = 1;
    614 	}
    615 	Flag(FERREXIT) = errexit;
    616 
    617 	if (Flag(FTALKING) && s)
    618 		hist_init(s);
    619 	else
    620 		/* set after ENV */
    621 		Flag(FTRACKALL) = 1;
    622 
    623 	alarm_init();
    624 
    625 	*sp = s;
    626 	*lp = l;
    627 	return (0);
    628 }
    629 
    630 /* this indirection barrier reduces stack usage during normal operation */
    631 
    632 int
    633 main(int argc, const char *argv[])
    634 {
    635 	int rv;
    636 	Source *s;
    637 	struct block *l;
    638 
    639 	if ((rv = main_init(argc, argv, &s, &l)) == 0) {
    640 		if (Flag(FAS_BUILTIN)) {
    641 			rv = shcomexec(l->argv);
    642 		} else {
    643 			shell(s, true);
    644 			/* NOTREACHED */
    645 		}
    646 	}
    647 	return (rv);
    648 }
    649 
    650 int
    651 include(const char *name, int argc, const char **argv, bool intr_ok)
    652 {
    653 	Source *volatile s = NULL;
    654 	struct shf *shf;
    655 	const char **volatile old_argv;
    656 	volatile int old_argc;
    657 	int i;
    658 
    659 	shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
    660 	if (shf == NULL)
    661 		return (-1);
    662 
    663 	if (argv) {
    664 		old_argv = e->loc->argv;
    665 		old_argc = e->loc->argc;
    666 	} else {
    667 		old_argv = NULL;
    668 		old_argc = 0;
    669 	}
    670 	newenv(E_INCL);
    671 	if ((i = kshsetjmp(e->jbuf))) {
    672 		quitenv(s ? s->u.shf : NULL);
    673 		if (old_argv) {
    674 			e->loc->argv = old_argv;
    675 			e->loc->argc = old_argc;
    676 		}
    677 		switch (i) {
    678 		case LRETURN:
    679 		case LERROR:
    680 			/* see below */
    681 			return (exstat & 0xFF);
    682 		case LINTR:
    683 			/*
    684 			 * intr_ok is set if we are including .profile or $ENV.
    685 			 * If user ^Cs out, we don't want to kill the shell...
    686 			 */
    687 			if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
    688 				return (1);
    689 			/* FALLTHROUGH */
    690 		case LEXIT:
    691 		case LLEAVE:
    692 		case LSHELL:
    693 			unwind(i);
    694 			/* NOTREACHED */
    695 		default:
    696 			internal_errorf("%s %d", "include", i);
    697 			/* NOTREACHED */
    698 		}
    699 	}
    700 	if (argv) {
    701 		e->loc->argv = argv;
    702 		e->loc->argc = argc;
    703 	}
    704 	s = pushs(SFILE, ATEMP);
    705 	s->u.shf = shf;
    706 	strdupx(s->file, name, ATEMP);
    707 	i = shell(s, false);
    708 	quitenv(s->u.shf);
    709 	if (old_argv) {
    710 		e->loc->argv = old_argv;
    711 		e->loc->argc = old_argc;
    712 	}
    713 	/* & 0xff to ensure value not -1 */
    714 	return (i & 0xFF);
    715 }
    716 
    717 /* spawn a command into a shell optionally keeping track of the line number */
    718 int
    719 command(const char *comm, int line)
    720 {
    721 	Source *s;
    722 
    723 	s = pushs(SSTRING, ATEMP);
    724 	s->start = s->str = comm;
    725 	s->line = line;
    726 	return (shell(s, false));
    727 }
    728 
    729 /*
    730  * run the commands from the input source, returning status.
    731  */
    732 int
    733 shell(Source * volatile s, volatile bool toplevel)
    734 {
    735 	struct op *t;
    736 	volatile bool wastty = tobool(s->flags & SF_TTY);
    737 	volatile uint8_t attempts = 13;
    738 	volatile bool interactive = Flag(FTALKING) && toplevel;
    739 	volatile bool sfirst = true;
    740 	Source *volatile old_source = source;
    741 	int i;
    742 
    743 	newenv(E_PARSE);
    744 	if (interactive)
    745 		really_exit = false;
    746 	switch ((i = kshsetjmp(e->jbuf))) {
    747 	case 0:
    748 		break;
    749 	case LINTR:
    750 		/* we get here if SIGINT not caught or ignored */
    751 	case LERROR:
    752 	case LSHELL:
    753 		if (interactive) {
    754 			if (i == LINTR)
    755 				shellf("\n");
    756 			/*
    757 			 * Reset any eof that was read as part of a
    758 			 * multiline command.
    759 			 */
    760 			if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
    761 				s->type = SSTDIN;
    762 			/*
    763 			 * Used by exit command to get back to
    764 			 * top level shell. Kind of strange since
    765 			 * interactive is set if we are reading from
    766 			 * a tty, but to have stopped jobs, one only
    767 			 * needs FMONITOR set (not FTALKING/SF_TTY)...
    768 			 */
    769 			/* toss any input we have so far */
    770 			yyrecursive_pop(true);
    771 			s->start = s->str = null;
    772 			retrace_info = NULL;
    773 			herep = heres;
    774 			break;
    775 		}
    776 		/* FALLTHROUGH */
    777 	case LEXIT:
    778 	case LLEAVE:
    779 	case LRETURN:
    780 		source = old_source;
    781 		quitenv(NULL);
    782 		/* keep on going */
    783 		unwind(i);
    784 		/* NOTREACHED */
    785 	default:
    786 		source = old_source;
    787 		quitenv(NULL);
    788 		internal_errorf("%s %d", "shell", i);
    789 		/* NOTREACHED */
    790 	}
    791 	while (/* CONSTCOND */ 1) {
    792 		if (trap)
    793 			runtraps(0);
    794 
    795 		if (s->next == NULL) {
    796 			if (Flag(FVERBOSE))
    797 				s->flags |= SF_ECHO;
    798 			else
    799 				s->flags &= ~SF_ECHO;
    800 		}
    801 		if (interactive) {
    802 			j_notify();
    803 			set_prompt(PS1, s);
    804 		}
    805 		t = compile(s, sfirst);
    806 		sfirst = false;
    807 		if (!t)
    808 			goto source_no_tree;
    809 		if (t->type == TEOF) {
    810 			if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
    811 				shellf("Use 'exit' to leave mksh\n");
    812 				s->type = SSTDIN;
    813 			} else if (wastty && !really_exit &&
    814 			    j_stopped_running()) {
    815 				really_exit = true;
    816 				s->type = SSTDIN;
    817 			} else {
    818 				/*
    819 				 * this for POSIX which says EXIT traps
    820 				 * shall be taken in the environment
    821 				 * immediately after the last command
    822 				 * executed.
    823 				 */
    824 				if (toplevel)
    825 					unwind(LEXIT);
    826 				break;
    827 			}
    828 		} else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
    829 			t->u.evalflags |= DOTCOMEXEC;
    830 		if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
    831 			exstat = execute(t, 0, NULL) & 0xFF;
    832 
    833 		if (t->type != TEOF && interactive && really_exit)
    834 			really_exit = false;
    835 
    836  source_no_tree:
    837 		reclaim();
    838 	}
    839 	quitenv(NULL);
    840 	source = old_source;
    841 	return (exstat & 0xFF);
    842 }
    843 
    844 /* return to closest error handler or shell(), exit if none found */
    845 /* note: i MUST NOT be 0 */
    846 void
    847 unwind(int i)
    848 {
    849 	/*
    850 	 * This is a kludge. We need to restore everything that was
    851 	 * changed in the new environment, see cid 1005090337C7A669439
    852 	 * and 10050903386452ACBF1, but fail to even save things most of
    853 	 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
    854 	 * which needs to be restored thus (related to Debian #696823).
    855 	 * We did not save the shell flags, so we use a special or'd
    856 	 * value here... this is mostly to clean up behind *other*
    857 	 * callers of unwind(LERROR) here; exec.c has the regular case.
    858 	 */
    859 	if (Flag(FERREXIT) & 0x80) {
    860 		/* GNU bash does not run this trapsig */
    861 		trapsig(ksh_SIGERR);
    862 		Flag(FERREXIT) &= ~0x80;
    863 	}
    864 
    865 	/* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
    866 	if (i == LEXIT || ((i == LERROR || i == LINTR) &&
    867 	    sigtraps[ksh_SIGEXIT].trap &&
    868 	    (!Flag(FTALKING) || Flag(FERREXIT)))) {
    869 		++trap_nested;
    870 		runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
    871 		--trap_nested;
    872 		i = LLEAVE;
    873 	} else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
    874 		++trap_nested;
    875 		runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
    876 		--trap_nested;
    877 		i = LLEAVE;
    878 	}
    879 
    880 	while (/* CONSTCOND */ 1) {
    881 		switch (e->type) {
    882 		case E_PARSE:
    883 		case E_FUNC:
    884 		case E_INCL:
    885 		case E_LOOP:
    886 		case E_ERRH:
    887 			kshlongjmp(e->jbuf, i);
    888 			/* NOTREACHED */
    889 		case E_NONE:
    890 			if (i == LINTR)
    891 				e->flags |= EF_FAKE_SIGDIE;
    892 			/* FALLTHROUGH */
    893 		default:
    894 			quitenv(NULL);
    895 		}
    896 	}
    897 }
    898 
    899 void
    900 newenv(int type)
    901 {
    902 	struct env *ep;
    903 	char *cp;
    904 
    905 	/*
    906 	 * struct env includes ALLOC_ITEM for alignment constraints
    907 	 * so first get the actually used memory, then assign it
    908 	 */
    909 	cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
    910 	/* undo what alloc() did to the malloc result address */
    911 	ep = (void *)(cp - ALLOC_SIZE);
    912 	/* initialise public members of struct env (not the ALLOC_ITEM) */
    913 	ainit(&ep->area);
    914 	ep->oenv = e;
    915 	ep->loc = e->loc;
    916 	ep->savefd = NULL;
    917 	ep->temps = NULL;
    918 	ep->yyrecursive_statep = NULL;
    919 	ep->type = type;
    920 	ep->flags = 0;
    921 	/* jump buffer is invalid because flags == 0 */
    922 	e = ep;
    923 }
    924 
    925 void
    926 quitenv(struct shf *shf)
    927 {
    928 	struct env *ep = e;
    929 	char *cp;
    930 	int fd;
    931 
    932 	yyrecursive_pop(true);
    933 	while (ep->oenv && ep->oenv->loc != ep->loc)
    934 		popblock();
    935 	if (ep->savefd != NULL) {
    936 		for (fd = 0; fd < NUFILE; fd++)
    937 			/* if ep->savefd[fd] < 0, means fd was closed */
    938 			if (ep->savefd[fd])
    939 				restfd(fd, ep->savefd[fd]);
    940 		if (ep->savefd[2])
    941 			/* Clear any write errors */
    942 			shf_reopen(2, SHF_WR, shl_out);
    943 	}
    944 	/*
    945 	 * Bottom of the stack.
    946 	 * Either main shell is exiting or cleanup_parents_env() was called.
    947 	 */
    948 	if (ep->oenv == NULL) {
    949 #ifdef DEBUG_LEAKS
    950 		int i;
    951 #endif
    952 
    953 		if (ep->type == E_NONE) {
    954 			/* Main shell exiting? */
    955 #if HAVE_PERSISTENT_HISTORY
    956 			if (Flag(FTALKING))
    957 				hist_finish();
    958 #endif
    959 			j_exit();
    960 			if (ep->flags & EF_FAKE_SIGDIE) {
    961 				int sig = (exstat & 0xFF) - 128;
    962 
    963 				/*
    964 				 * ham up our death a bit (AT&T ksh
    965 				 * only seems to do this for SIGTERM)
    966 				 * Don't do it for SIGQUIT, since we'd
    967 				 * dump a core..
    968 				 */
    969 				if ((sig == SIGINT || sig == SIGTERM) &&
    970 				    (kshpgrp == kshpid)) {
    971 					setsig(&sigtraps[sig], SIG_DFL,
    972 					    SS_RESTORE_CURR | SS_FORCE);
    973 					kill(0, sig);
    974 				}
    975 			}
    976 		}
    977 		if (shf)
    978 			shf_close(shf);
    979 		reclaim();
    980 #ifdef DEBUG_LEAKS
    981 #ifndef MKSH_NO_CMDLINE_EDITING
    982 		x_done();
    983 #endif
    984 #ifndef MKSH_NOPROSPECTOFWORK
    985 		/* block at least SIGCHLD during/after afreeall */
    986 		sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
    987 #endif
    988 		afreeall(APERM);
    989 		for (fd = 3; fd < NUFILE; fd++)
    990 			if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
    991 			    (i & FD_CLOEXEC))
    992 				close(fd);
    993 		close(2);
    994 		close(1);
    995 		close(0);
    996 #endif
    997 		exit(exstat & 0xFF);
    998 	}
    999 	if (shf)
   1000 		shf_close(shf);
   1001 	reclaim();
   1002 
   1003 	e = e->oenv;
   1004 
   1005 	/* free the struct env - tricky due to the ALLOC_ITEM inside */
   1006 	cp = (void *)ep;
   1007 	afree(cp + ALLOC_SIZE, ATEMP);
   1008 }
   1009 
   1010 /* Called after a fork to cleanup stuff left over from parents environment */
   1011 void
   1012 cleanup_parents_env(void)
   1013 {
   1014 	struct env *ep;
   1015 	int fd;
   1016 
   1017 	mkssert(e != NULL);
   1018 
   1019 	/*
   1020 	 * Don't clean up temporary files - parent will probably need them.
   1021 	 * Also, can't easily reclaim memory since variables, etc. could be
   1022 	 * anywhere.
   1023 	 */
   1024 
   1025 	/* close all file descriptors hiding in savefd */
   1026 	for (ep = e; ep; ep = ep->oenv) {
   1027 		if (ep->savefd) {
   1028 			for (fd = 0; fd < NUFILE; fd++)
   1029 				if (ep->savefd[fd] > 0)
   1030 					close(ep->savefd[fd]);
   1031 			afree(ep->savefd, &ep->area);
   1032 			ep->savefd = NULL;
   1033 		}
   1034 #ifdef DEBUG_LEAKS
   1035 		if (ep->type != E_NONE)
   1036 			ep->type = E_GONE;
   1037 #endif
   1038 	}
   1039 #ifndef DEBUG_LEAKS
   1040 	e->oenv = NULL;
   1041 #endif
   1042 }
   1043 
   1044 /* Called just before an execve cleanup stuff temporary files */
   1045 void
   1046 cleanup_proc_env(void)
   1047 {
   1048 	struct env *ep;
   1049 
   1050 	for (ep = e; ep; ep = ep->oenv)
   1051 		remove_temps(ep->temps);
   1052 }
   1053 
   1054 /* remove temp files and free ATEMP Area */
   1055 static void
   1056 reclaim(void)
   1057 {
   1058 	struct block *l;
   1059 
   1060 	while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
   1061 		e->loc = l->next;
   1062 		afreeall(&l->area);
   1063 	}
   1064 
   1065 	remove_temps(e->temps);
   1066 	e->temps = NULL;
   1067 	afreeall(&e->area);
   1068 }
   1069 
   1070 static void
   1071 remove_temps(struct temp *tp)
   1072 {
   1073 	for (; tp != NULL; tp = tp->next)
   1074 		if (tp->pid == procpid)
   1075 			unlink(tp->tffn);
   1076 }
   1077 
   1078 /*
   1079  * Initialise tty_fd. Used for tracking the size of the terminal,
   1080  * saving/resetting tty modes upon forground job completion, and
   1081  * for setting up the tty process group. Return values:
   1082  *	0 = got controlling tty
   1083  *	1 = got terminal but no controlling tty
   1084  *	2 = cannot find a terminal
   1085  *	3 = cannot dup fd
   1086  *	4 = cannot make fd close-on-exec
   1087  * An existing tty_fd is cached if no "better" one could be found,
   1088  * i.e. if tty_devtty was already set or the new would not set it.
   1089  */
   1090 int
   1091 tty_init_fd(void)
   1092 {
   1093 	int fd, rv, eno = 0;
   1094 	bool do_close = false, is_devtty = true;
   1095 
   1096 	if (tty_devtty) {
   1097 		/* already got a tty which is /dev/tty */
   1098 		return (0);
   1099 	}
   1100 
   1101 #ifdef _UWIN
   1102 	/*XXX imake style */
   1103 	if (isatty(3)) {
   1104 		/* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
   1105 		fd = 3;
   1106 		goto got_fd;
   1107 	}
   1108 #endif
   1109 	if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
   1110 		do_close = true;
   1111 		goto got_fd;
   1112 	}
   1113 	eno = errno;
   1114 
   1115 	if (tty_fd >= 0) {
   1116 		/* already got a non-devtty one */
   1117 		rv = 1;
   1118 		goto out;
   1119 	}
   1120 	is_devtty = false;
   1121 
   1122 	if (isatty((fd = 0)) || isatty((fd = 2)))
   1123 		goto got_fd;
   1124 	/* cannot find one */
   1125 	rv = 2;
   1126 	/* assert: do_close == false */
   1127 	goto out;
   1128 
   1129  got_fd:
   1130 	if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
   1131 		eno = errno;
   1132 		rv = 3;
   1133 		goto out;
   1134 	}
   1135 	if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
   1136 		eno = errno;
   1137 		close(rv);
   1138 		rv = 4;
   1139 		goto out;
   1140 	}
   1141 	tty_fd = rv;
   1142 	tty_devtty = is_devtty;
   1143 	rv = eno = 0;
   1144  out:
   1145 	if (do_close)
   1146 		close(fd);
   1147 	errno = eno;
   1148 	return (rv);
   1149 }
   1150 
   1151 /* A shell error occurred (eg, syntax error, etc.) */
   1152 
   1153 #define VWARNINGF_ERRORPREFIX	1
   1154 #define VWARNINGF_FILELINE	2
   1155 #define VWARNINGF_BUILTIN	4
   1156 #define VWARNINGF_INTERNAL	8
   1157 
   1158 static void vwarningf(unsigned int, const char *, va_list)
   1159     MKSH_A_FORMAT(__printf__, 2, 0);
   1160 
   1161 static void
   1162 vwarningf(unsigned int flags, const char *fmt, va_list ap)
   1163 {
   1164 	if (fmt) {
   1165 		if (flags & VWARNINGF_INTERNAL)
   1166 			shf_fprintf(shl_out, "internal error: ");
   1167 		if (flags & VWARNINGF_ERRORPREFIX)
   1168 			error_prefix(tobool(flags & VWARNINGF_FILELINE));
   1169 		if ((flags & VWARNINGF_BUILTIN) &&
   1170 		    /* not set when main() calls parse_args() */
   1171 		    builtin_argv0 && builtin_argv0 != kshname)
   1172 			shf_fprintf(shl_out, "%s: ", builtin_argv0);
   1173 		shf_vfprintf(shl_out, fmt, ap);
   1174 		shf_putchar('\n', shl_out);
   1175 	}
   1176 	shf_flush(shl_out);
   1177 }
   1178 
   1179 void
   1180 errorfx(int rc, const char *fmt, ...)
   1181 {
   1182 	va_list va;
   1183 
   1184 	exstat = rc;
   1185 
   1186 	/* debugging: note that stdout not valid */
   1187 	shl_stdout_ok = false;
   1188 
   1189 	va_start(va, fmt);
   1190 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
   1191 	va_end(va);
   1192 	unwind(LERROR);
   1193 }
   1194 
   1195 void
   1196 errorf(const char *fmt, ...)
   1197 {
   1198 	va_list va;
   1199 
   1200 	exstat = 1;
   1201 
   1202 	/* debugging: note that stdout not valid */
   1203 	shl_stdout_ok = false;
   1204 
   1205 	va_start(va, fmt);
   1206 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
   1207 	va_end(va);
   1208 	unwind(LERROR);
   1209 }
   1210 
   1211 /* like errorf(), but no unwind is done */
   1212 void
   1213 warningf(bool fileline, const char *fmt, ...)
   1214 {
   1215 	va_list va;
   1216 
   1217 	va_start(va, fmt);
   1218 	vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
   1219 	    fmt, va);
   1220 	va_end(va);
   1221 }
   1222 
   1223 /*
   1224  * Used by built-in utilities to prefix shell and utility name to message
   1225  * (also unwinds environments for special builtins).
   1226  */
   1227 void
   1228 bi_errorf(const char *fmt, ...)
   1229 {
   1230 	va_list va;
   1231 
   1232 	/* debugging: note that stdout not valid */
   1233 	shl_stdout_ok = false;
   1234 
   1235 	exstat = 1;
   1236 
   1237 	va_start(va, fmt);
   1238 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
   1239 	    VWARNINGF_BUILTIN, fmt, va);
   1240 	va_end(va);
   1241 
   1242 	/*
   1243 	 * POSIX special builtins and ksh special builtins cause
   1244 	 * non-interactive shells to exit.
   1245 	 * XXX odd use of KEEPASN; also may not want LERROR here
   1246 	 */
   1247 	if (builtin_flag & SPEC_BI) {
   1248 		builtin_argv0 = NULL;
   1249 		unwind(LERROR);
   1250 	}
   1251 }
   1252 
   1253 /* Called when something that shouldn't happen does */
   1254 void
   1255 internal_errorf(const char *fmt, ...)
   1256 {
   1257 	va_list va;
   1258 
   1259 	va_start(va, fmt);
   1260 	vwarningf(VWARNINGF_INTERNAL, fmt, va);
   1261 	va_end(va);
   1262 	unwind(LERROR);
   1263 }
   1264 
   1265 void
   1266 internal_warningf(const char *fmt, ...)
   1267 {
   1268 	va_list va;
   1269 
   1270 	va_start(va, fmt);
   1271 	vwarningf(VWARNINGF_INTERNAL, fmt, va);
   1272 	va_end(va);
   1273 }
   1274 
   1275 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
   1276 void
   1277 error_prefix(bool fileline)
   1278 {
   1279 	/* Avoid foo: foo[2]: ... */
   1280 	if (!fileline || !source || !source->file ||
   1281 	    strcmp(source->file, kshname) != 0)
   1282 		shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
   1283 	if (fileline && source && source->file != NULL) {
   1284 		shf_fprintf(shl_out, "%s[%d]: ", source->file,
   1285 		    source->errline > 0 ? source->errline : source->line);
   1286 		source->errline = 0;
   1287 	}
   1288 }
   1289 
   1290 /* printf to shl_out (stderr) with flush */
   1291 void
   1292 shellf(const char *fmt, ...)
   1293 {
   1294 	va_list va;
   1295 
   1296 	if (!initio_done)
   1297 		/* shl_out may not be set up yet... */
   1298 		return;
   1299 	va_start(va, fmt);
   1300 	shf_vfprintf(shl_out, fmt, va);
   1301 	va_end(va);
   1302 	shf_flush(shl_out);
   1303 }
   1304 
   1305 /* printf to shl_stdout (stdout) */
   1306 void
   1307 shprintf(const char *fmt, ...)
   1308 {
   1309 	va_list va;
   1310 
   1311 	if (!shl_stdout_ok)
   1312 		internal_errorf("shl_stdout not valid");
   1313 	va_start(va, fmt);
   1314 	shf_vfprintf(shl_stdout, fmt, va);
   1315 	va_end(va);
   1316 }
   1317 
   1318 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
   1319 int
   1320 can_seek(int fd)
   1321 {
   1322 	struct stat statb;
   1323 
   1324 	return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
   1325 	    SHF_UNBUF : 0);
   1326 }
   1327 
   1328 #ifdef DF
   1329 int shl_dbg_fd;
   1330 #define NSHF_IOB 4
   1331 #else
   1332 #define NSHF_IOB 3
   1333 #endif
   1334 struct shf shf_iob[NSHF_IOB];
   1335 
   1336 void
   1337 initio(void)
   1338 {
   1339 #ifdef DF
   1340 	const char *lfp;
   1341 #endif
   1342 
   1343 	/* force buffer allocation */
   1344 	shf_fdopen(1, SHF_WR, shl_stdout);
   1345 	shf_fdopen(2, SHF_WR, shl_out);
   1346 	shf_fdopen(2, SHF_WR, shl_xtrace);
   1347 #ifdef DF
   1348 	if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
   1349 		if ((lfp = getenv("HOME")) == NULL || *lfp != '/')
   1350 			errorf("cannot get home directory");
   1351 		lfp = shf_smprintf("%s/mksh-dbg.txt", lfp);
   1352 	}
   1353 
   1354 	if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
   1355 		errorf("cannot open debug output file %s", lfp);
   1356 	if (shl_dbg_fd < FDBASE) {
   1357 		int nfd;
   1358 
   1359 		nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
   1360 		close(shl_dbg_fd);
   1361 		if ((shl_dbg_fd = nfd) == -1)
   1362 			errorf("cannot dup debug output file");
   1363 	}
   1364 	fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
   1365 	shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
   1366 	DF("=== open ===");
   1367 #endif
   1368 	initio_done = true;
   1369 }
   1370 
   1371 /* A dup2() with error checking */
   1372 int
   1373 ksh_dup2(int ofd, int nfd, bool errok)
   1374 {
   1375 	int rv;
   1376 
   1377 	if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
   1378 		errorf("too many files open in shell");
   1379 
   1380 #ifdef __ultrix
   1381 	/*XXX imake style */
   1382 	if (rv >= 0)
   1383 		fcntl(nfd, F_SETFD, 0);
   1384 #endif
   1385 
   1386 	return (rv);
   1387 }
   1388 
   1389 /*
   1390  * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
   1391  * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
   1392  */
   1393 short
   1394 savefd(int fd)
   1395 {
   1396 	int nfd = fd;
   1397 
   1398 	if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
   1399 	    errno == EBADF)
   1400 		return (-1);
   1401 	if (nfd < 0 || nfd > SHRT_MAX)
   1402 		errorf("too many files open in shell");
   1403 	fcntl(nfd, F_SETFD, FD_CLOEXEC);
   1404 	return ((short)nfd);
   1405 }
   1406 
   1407 void
   1408 restfd(int fd, int ofd)
   1409 {
   1410 	if (fd == 2)
   1411 		shf_flush(&shf_iob[/* fd */ 2]);
   1412 	if (ofd < 0)
   1413 		/* original fd closed */
   1414 		close(fd);
   1415 	else if (fd != ofd) {
   1416 		/*XXX: what to do if this dup fails? */
   1417 		ksh_dup2(ofd, fd, true);
   1418 		close(ofd);
   1419 	}
   1420 }
   1421 
   1422 void
   1423 openpipe(int *pv)
   1424 {
   1425 	int lpv[2];
   1426 
   1427 	if (pipe(lpv) < 0)
   1428 		errorf("can't create pipe - try again");
   1429 	pv[0] = savefd(lpv[0]);
   1430 	if (pv[0] != lpv[0])
   1431 		close(lpv[0]);
   1432 	pv[1] = savefd(lpv[1]);
   1433 	if (pv[1] != lpv[1])
   1434 		close(lpv[1]);
   1435 }
   1436 
   1437 void
   1438 closepipe(int *pv)
   1439 {
   1440 	close(pv[0]);
   1441 	close(pv[1]);
   1442 }
   1443 
   1444 /*
   1445  * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
   1446  * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
   1447  */
   1448 int
   1449 check_fd(const char *name, int mode, const char **emsgp)
   1450 {
   1451 	int fd, fl;
   1452 
   1453 	if (name[0] == 'p' && !name[1])
   1454 		return (coproc_getfd(mode, emsgp));
   1455 	for (fd = 0; ksh_isdigit(*name); ++name)
   1456 		fd = (fd * 10) + *name - '0';
   1457 	if (*name || fd >= FDBASE) {
   1458 		if (emsgp)
   1459 			*emsgp = "illegal file descriptor name";
   1460 		return (-1);
   1461 	}
   1462 	if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
   1463 		if (emsgp)
   1464 			*emsgp = "bad file descriptor";
   1465 		return (-1);
   1466 	}
   1467 	fl &= O_ACCMODE;
   1468 	/*
   1469 	 * X_OK is a kludge to disable this check for dups (x<&1):
   1470 	 * historical shells never did this check (XXX don't know what
   1471 	 * POSIX has to say).
   1472 	 */
   1473 	if (!(mode & X_OK) && fl != O_RDWR && (
   1474 	    ((mode & R_OK) && fl != O_RDONLY) ||
   1475 	    ((mode & W_OK) && fl != O_WRONLY))) {
   1476 		if (emsgp)
   1477 			*emsgp = (fl == O_WRONLY) ?
   1478 			    "fd not open for reading" :
   1479 			    "fd not open for writing";
   1480 		return (-1);
   1481 	}
   1482 	return (fd);
   1483 }
   1484 
   1485 /* Called once from main */
   1486 void
   1487 coproc_init(void)
   1488 {
   1489 	coproc.read = coproc.readw = coproc.write = -1;
   1490 	coproc.njobs = 0;
   1491 	coproc.id = 0;
   1492 }
   1493 
   1494 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
   1495 void
   1496 coproc_read_close(int fd)
   1497 {
   1498 	if (coproc.read >= 0 && fd == coproc.read) {
   1499 		coproc_readw_close(fd);
   1500 		close(coproc.read);
   1501 		coproc.read = -1;
   1502 	}
   1503 }
   1504 
   1505 /*
   1506  * Called by c_read() and by iosetup() to close the other side of the
   1507  * read pipe, so reads will actually terminate.
   1508  */
   1509 void
   1510 coproc_readw_close(int fd)
   1511 {
   1512 	if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
   1513 		close(coproc.readw);
   1514 		coproc.readw = -1;
   1515 	}
   1516 }
   1517 
   1518 /*
   1519  * Called by c_print when a write to a fd fails with EPIPE and by iosetup
   1520  * when co-process input is dup'd
   1521  */
   1522 void
   1523 coproc_write_close(int fd)
   1524 {
   1525 	if (coproc.write >= 0 && fd == coproc.write) {
   1526 		close(coproc.write);
   1527 		coproc.write = -1;
   1528 	}
   1529 }
   1530 
   1531 /*
   1532  * Called to check for existence of/value of the co-process file descriptor.
   1533  * (Used by check_fd() and by c_read/c_print to deal with -p option).
   1534  */
   1535 int
   1536 coproc_getfd(int mode, const char **emsgp)
   1537 {
   1538 	int fd = (mode & R_OK) ? coproc.read : coproc.write;
   1539 
   1540 	if (fd >= 0)
   1541 		return (fd);
   1542 	if (emsgp)
   1543 		*emsgp = "no coprocess";
   1544 	return (-1);
   1545 }
   1546 
   1547 /*
   1548  * called to close file descriptors related to the coprocess (if any)
   1549  * Should be called with SIGCHLD blocked.
   1550  */
   1551 void
   1552 coproc_cleanup(int reuse)
   1553 {
   1554 	/* This to allow co-processes to share output pipe */
   1555 	if (!reuse || coproc.readw < 0 || coproc.read < 0) {
   1556 		if (coproc.read >= 0) {
   1557 			close(coproc.read);
   1558 			coproc.read = -1;
   1559 		}
   1560 		if (coproc.readw >= 0) {
   1561 			close(coproc.readw);
   1562 			coproc.readw = -1;
   1563 		}
   1564 	}
   1565 	if (coproc.write >= 0) {
   1566 		close(coproc.write);
   1567 		coproc.write = -1;
   1568 	}
   1569 }
   1570 
   1571 struct temp *
   1572 maketemp(Area *ap, Temp_type type, struct temp **tlist)
   1573 {
   1574 	char *cp;
   1575 	size_t len;
   1576 	int i, j;
   1577 	struct temp *tp;
   1578 	const char *dir;
   1579 	struct stat sb;
   1580 
   1581 	dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
   1582 	/* add "/shXXXXXX.tmp" plus NUL */
   1583 	len = strlen(dir);
   1584 	checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
   1585 	tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
   1586 
   1587 	tp->shf = NULL;
   1588 	tp->pid = procpid;
   1589 	tp->type = type;
   1590 
   1591 	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
   1592 		tp->tffn[0] = '\0';
   1593 		goto maketemp_out;
   1594 	}
   1595 
   1596 	cp = (void *)tp;
   1597 	cp += offsetof(struct temp, tffn[0]);
   1598 	memcpy(cp, dir, len);
   1599 	cp += len;
   1600 	memcpy(cp, "/shXXXXXX.tmp", 14);
   1601 	/* point to the first of six Xes */
   1602 	cp += 3;
   1603 	/* generate random part of filename */
   1604 	len = -1;
   1605 	do {
   1606 		i = rndget() % 36;
   1607 		cp[++len] = i < 26 ? 'a' + i : '0' + i - 26;
   1608 	} while (len < 5);
   1609 
   1610 	/* cyclically attempt to open a temporary file */
   1611 	while ((i = open(tp->tffn, O_CREAT | O_EXCL | O_RDWR | O_BINARY,
   1612 	    0600)) < 0) {
   1613 		if (errno != EEXIST)
   1614 			goto maketemp_out;
   1615 		/* count down from z to a then from 9 to 0 */
   1616 		while (cp[len] == '0')
   1617 			if (!len--)
   1618 				goto maketemp_out;
   1619 		if (cp[len] == 'a')
   1620 			cp[len] = '9';
   1621 		else
   1622 			--cp[len];
   1623 		/* do another cycle */
   1624 	}
   1625 
   1626 	if (type == TT_FUNSUB) {
   1627 		/* map us high and mark as close-on-exec */
   1628 		if ((j = savefd(i)) != i) {
   1629 			close(i);
   1630 			i = j;
   1631 		}
   1632 
   1633 		/* operation mode for the shf */
   1634 		j = SHF_RD;
   1635 	} else
   1636 		j = SHF_WR;
   1637 
   1638 	/* shf_fdopen cannot fail, so no fd leak */
   1639 	tp->shf = shf_fdopen(i, j, NULL);
   1640 
   1641  maketemp_out:
   1642 	tp->next = *tlist;
   1643 	*tlist = tp;
   1644 	return (tp);
   1645 }
   1646 
   1647 /*
   1648  * We use a similar collision resolution algorithm as Python 2.5.4
   1649  * but with a slightly tweaked implementation written from scratch.
   1650  */
   1651 
   1652 #define	INIT_TBLSHIFT	3	/* initial table shift (2^3 = 8) */
   1653 #define PERTURB_SHIFT	5	/* see Python 2.5.4 Objects/dictobject.c */
   1654 
   1655 static void tgrow(struct table *);
   1656 static int tnamecmp(const void *, const void *);
   1657 
   1658 static void
   1659 tgrow(struct table *tp)
   1660 {
   1661 	size_t i, j, osize, mask, perturb;
   1662 	struct tbl *tblp, **pp;
   1663 	struct tbl **ntblp, **otblp = tp->tbls;
   1664 
   1665 	if (tp->tshift > 29)
   1666 		internal_errorf("hash table size limit reached");
   1667 
   1668 	/* calculate old size, new shift and new size */
   1669 	osize = (size_t)1 << (tp->tshift++);
   1670 	i = osize << 1;
   1671 
   1672 	ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
   1673 	/* multiplication cannot overflow: alloc2 checked that */
   1674 	memset(ntblp, 0, i * sizeof(struct tbl *));
   1675 
   1676 	/* table can get very full when reaching its size limit */
   1677 	tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
   1678 	    /* but otherwise, only 75% */
   1679 	    ((i * 3) / 4);
   1680 	tp->tbls = ntblp;
   1681 	if (otblp == NULL)
   1682 		return;
   1683 
   1684 	mask = i - 1;
   1685 	for (i = 0; i < osize; i++)
   1686 		if ((tblp = otblp[i]) != NULL) {
   1687 			if ((tblp->flag & DEFINED)) {
   1688 				/* search for free hash table slot */
   1689 				j = perturb = tblp->ua.hval;
   1690 				goto find_first_empty_slot;
   1691  find_next_empty_slot:
   1692 				j = (j << 2) + j + perturb + 1;
   1693 				perturb >>= PERTURB_SHIFT;
   1694  find_first_empty_slot:
   1695 				pp = &ntblp[j & mask];
   1696 				if (*pp != NULL)
   1697 					goto find_next_empty_slot;
   1698 				/* found an empty hash table slot */
   1699 				*pp = tblp;
   1700 				tp->nfree--;
   1701 			} else if (!(tblp->flag & FINUSE)) {
   1702 				afree(tblp, tp->areap);
   1703 			}
   1704 		}
   1705 	afree(otblp, tp->areap);
   1706 }
   1707 
   1708 void
   1709 ktinit(Area *ap, struct table *tp, uint8_t initshift)
   1710 {
   1711 	tp->areap = ap;
   1712 	tp->tbls = NULL;
   1713 	tp->tshift = ((initshift > INIT_TBLSHIFT) ?
   1714 	    initshift : INIT_TBLSHIFT) - 1;
   1715 	tgrow(tp);
   1716 }
   1717 
   1718 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
   1719 struct tbl *
   1720 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
   1721 {
   1722 	size_t j, perturb, mask;
   1723 	struct tbl **pp, *p;
   1724 
   1725 	mask = ((size_t)1 << (tp->tshift)) - 1;
   1726 	/* search for hash table slot matching name */
   1727 	j = perturb = h;
   1728 	goto find_first_slot;
   1729  find_next_slot:
   1730 	j = (j << 2) + j + perturb + 1;
   1731 	perturb >>= PERTURB_SHIFT;
   1732  find_first_slot:
   1733 	pp = &tp->tbls[j & mask];
   1734 	if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
   1735 	    strcmp(p->name, name)))
   1736 		goto find_next_slot;
   1737 	/* p == NULL if not found, correct found entry otherwise */
   1738 	if (ppp)
   1739 		*ppp = pp;
   1740 	return (p);
   1741 }
   1742 
   1743 /* table, name (key) to enter, hash(n) */
   1744 struct tbl *
   1745 ktenter(struct table *tp, const char *n, uint32_t h)
   1746 {
   1747 	struct tbl **pp, *p;
   1748 	size_t len;
   1749 
   1750  Search:
   1751 	if ((p = ktscan(tp, n, h, &pp)))
   1752 		return (p);
   1753 
   1754 	if (tp->nfree == 0) {
   1755 		/* too full */
   1756 		tgrow(tp);
   1757 		goto Search;
   1758 	}
   1759 
   1760 	/* create new tbl entry */
   1761 	len = strlen(n);
   1762 	checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
   1763 	p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
   1764 	p->flag = 0;
   1765 	p->type = 0;
   1766 	p->areap = tp->areap;
   1767 	p->ua.hval = h;
   1768 	p->u2.field = 0;
   1769 	p->u.array = NULL;
   1770 	memcpy(p->name, n, len);
   1771 
   1772 	/* enter in tp->tbls */
   1773 	tp->nfree--;
   1774 	*pp = p;
   1775 	return (p);
   1776 }
   1777 
   1778 void
   1779 ktwalk(struct tstate *ts, struct table *tp)
   1780 {
   1781 	ts->left = (size_t)1 << (tp->tshift);
   1782 	ts->next = tp->tbls;
   1783 }
   1784 
   1785 struct tbl *
   1786 ktnext(struct tstate *ts)
   1787 {
   1788 	while (--ts->left >= 0) {
   1789 		struct tbl *p = *ts->next++;
   1790 		if (p != NULL && (p->flag & DEFINED))
   1791 			return (p);
   1792 	}
   1793 	return (NULL);
   1794 }
   1795 
   1796 static int
   1797 tnamecmp(const void *p1, const void *p2)
   1798 {
   1799 	const struct tbl *a = *((const struct tbl * const *)p1);
   1800 	const struct tbl *b = *((const struct tbl * const *)p2);
   1801 
   1802 	return (strcmp(a->name, b->name));
   1803 }
   1804 
   1805 struct tbl **
   1806 ktsort(struct table *tp)
   1807 {
   1808 	size_t i;
   1809 	struct tbl **p, **sp, **dp;
   1810 
   1811 	/*
   1812 	 * since the table is never entirely full, no need to reserve
   1813 	 * additional space for the trailing NULL appended below
   1814 	 */
   1815 	i = (size_t)1 << (tp->tshift);
   1816 	p = alloc2(i, sizeof(struct tbl *), ATEMP);
   1817 	sp = tp->tbls;		/* source */
   1818 	dp = p;			/* dest */
   1819 	while (i--)
   1820 		if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
   1821 		    ((*dp)->flag & ARRAY)))
   1822 			dp++;
   1823 	qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
   1824 	p[i] = NULL;
   1825 	return (p);
   1826 }
   1827 
   1828 #ifdef SIGWINCH
   1829 static void
   1830 x_sigwinch(int sig MKSH_A_UNUSED)
   1831 {
   1832 	/* this runs inside interrupt context, with errno saved */
   1833 
   1834 	got_winch = 1;
   1835 }
   1836 #endif
   1837 
   1838 #ifdef DF
   1839 void
   1840 DF(const char *fmt, ...)
   1841 {
   1842 	va_list args;
   1843 	struct timeval tv;
   1844 	mirtime_mjd mjd;
   1845 
   1846 	mksh_lockfd(shl_dbg_fd);
   1847 	mksh_TIME(tv);
   1848 	timet2mjd(&mjd, tv.tv_sec);
   1849 	shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
   1850 	    (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
   1851 	    (unsigned)mjd.sec % 60, (unsigned)getpid(),
   1852 	    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
   1853 	va_start(args, fmt);
   1854 	shf_vfprintf(shl_dbg, fmt, args);
   1855 	va_end(args);
   1856 	shf_putc('\n', shl_dbg);
   1857 	shf_flush(shl_dbg);
   1858 	mksh_unlkfd(shl_dbg_fd);
   1859 }
   1860 #endif
   1861 
   1862 void
   1863 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
   1864 {
   1865 	mksh_ttyst cb;
   1866 
   1867 	if (ocb)
   1868 		mksh_tcget(fd, ocb);
   1869 	else
   1870 		ocb = &tty_state;
   1871 
   1872 	cb = *ocb;
   1873 	if (forread) {
   1874 		cb.c_iflag &= ~(ISTRIP);
   1875 		cb.c_lflag &= ~(ICANON) | ECHO;
   1876 	} else {
   1877 		cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
   1878 		cb.c_lflag &= ~(ISIG | ICANON | ECHO);
   1879 	}
   1880 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
   1881 	/* OSF/1 processes lnext when ~icanon */
   1882 	cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
   1883 #endif
   1884 	/* SunOS 4.1.x & OSF/1 processes discard(flush) when ~icanon */
   1885 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
   1886 	cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
   1887 #endif
   1888 	cb.c_cc[VTIME] = 0;
   1889 	cb.c_cc[VMIN] = 1;
   1890 
   1891 	mksh_tcset(fd, &cb);
   1892 }
   1893