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