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