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