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