• 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))
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 	afreeall(&e->area);
1202 }
1203 
1204 static void
remove_temps(struct temp * tp)1205 remove_temps(struct temp *tp)
1206 {
1207 	while (tp) {
1208 		if (tp->pid == procpid)
1209 			unlink(tp->tffn);
1210 		tp = tp->next;
1211 	}
1212 }
1213 
1214 /*
1215  * Initialise tty_fd. Used for tracking the size of the terminal,
1216  * saving/resetting tty modes upon foreground job completion, and
1217  * for setting up the tty process group. Return values:
1218  *	0 = got controlling tty
1219  *	1 = got terminal but no controlling tty
1220  *	2 = cannot find a terminal
1221  *	3 = cannot dup fd
1222  *	4 = cannot make fd close-on-exec
1223  * An existing tty_fd is cached if no "better" one could be found,
1224  * i.e. if tty_devtty was already set or the new would not set it.
1225  */
1226 int
tty_init_fd(void)1227 tty_init_fd(void)
1228 {
1229 	int fd, rv, eno = 0;
1230 	bool do_close = false, is_devtty = true;
1231 
1232 	if (tty_devtty) {
1233 		/* already got a tty which is /dev/tty */
1234 		return (0);
1235 	}
1236 
1237 #ifdef _UWIN
1238 	/*XXX imake style */
1239 	if (isatty(3)) {
1240 		/* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
1241 		fd = 3;
1242 		goto got_fd;
1243 	}
1244 #endif
1245 	if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
1246 		do_close = true;
1247 		goto got_fd;
1248 	}
1249 	eno = errno;
1250 
1251 	if (tty_fd >= 0) {
1252 		/* already got a non-devtty one */
1253 		rv = 1;
1254 		goto out;
1255 	}
1256 	is_devtty = false;
1257 
1258 	if (isatty((fd = 0)) || isatty((fd = 2)))
1259 		goto got_fd;
1260 	/* cannot find one */
1261 	rv = 2;
1262 	/* assert: do_close == false */
1263 	goto out;
1264 
1265  got_fd:
1266 	if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1267 		eno = errno;
1268 		rv = 3;
1269 		goto out;
1270 	}
1271 	if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1272 		eno = errno;
1273 		close(rv);
1274 		rv = 4;
1275 		goto out;
1276 	}
1277 	tty_fd = rv;
1278 	tty_devtty = is_devtty;
1279 	rv = eno = 0;
1280  out:
1281 	if (do_close)
1282 		close(fd);
1283 	errno = eno;
1284 	return (rv);
1285 }
1286 
1287 /* A shell error occurred (eg, syntax error, etc.) */
1288 
1289 #define VWARNINGF_ERRORPREFIX	1
1290 #define VWARNINGF_FILELINE	2
1291 #define VWARNINGF_BUILTIN	4
1292 #define VWARNINGF_INTERNAL	8
1293 
1294 static void vwarningf(unsigned int, const char *, va_list)
1295     MKSH_A_FORMAT(__printf__, 2, 0);
1296 
1297 static void
vwarningf(unsigned int flags,const char * fmt,va_list ap)1298 vwarningf(unsigned int flags, const char *fmt, va_list ap)
1299 {
1300 	if (fmt) {
1301 		if (flags & VWARNINGF_INTERNAL)
1302 			shf_fprintf(shl_out, Tf_sD_, "internal error");
1303 		if (flags & VWARNINGF_ERRORPREFIX)
1304 			error_prefix(tobool(flags & VWARNINGF_FILELINE));
1305 		if ((flags & VWARNINGF_BUILTIN) &&
1306 		    /* not set when main() calls parse_args() */
1307 		    builtin_argv0 && builtin_argv0 != kshname)
1308 			shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
1309 		shf_vfprintf(shl_out, fmt, ap);
1310 		shf_putchar('\n', shl_out);
1311 	}
1312 	shf_flush(shl_out);
1313 }
1314 
1315 void
errorfx(int rc,const char * fmt,...)1316 errorfx(int rc, const char *fmt, ...)
1317 {
1318 	va_list va;
1319 
1320 	exstat = rc;
1321 
1322 	/* debugging: note that stdout not valid */
1323 	shl_stdout_ok = false;
1324 
1325 	va_start(va, fmt);
1326 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1327 	va_end(va);
1328 	unwind(LERROR);
1329 }
1330 
1331 void
errorf(const char * fmt,...)1332 errorf(const char *fmt, ...)
1333 {
1334 	va_list va;
1335 
1336 	exstat = 1;
1337 
1338 	/* debugging: note that stdout not valid */
1339 	shl_stdout_ok = false;
1340 
1341 	va_start(va, fmt);
1342 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1343 	va_end(va);
1344 	unwind(LERROR);
1345 }
1346 
1347 /* like errorf(), but no unwind is done */
1348 void
warningf(bool fileline,const char * fmt,...)1349 warningf(bool fileline, const char *fmt, ...)
1350 {
1351 	va_list va;
1352 
1353 	va_start(va, fmt);
1354 	vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1355 	    fmt, va);
1356 	va_end(va);
1357 }
1358 
1359 /*
1360  * Used by built-in utilities to prefix shell and utility name to message
1361  * (also unwinds environments for special builtins).
1362  */
1363 void
bi_errorf(const char * fmt,...)1364 bi_errorf(const char *fmt, ...)
1365 {
1366 	va_list va;
1367 
1368 	/* debugging: note that stdout not valid */
1369 	shl_stdout_ok = false;
1370 
1371 	exstat = 1;
1372 
1373 	va_start(va, fmt);
1374 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1375 	    VWARNINGF_BUILTIN, fmt, va);
1376 	va_end(va);
1377 
1378 	/* POSIX special builtins cause non-interactive shells to exit */
1379 	if (builtin_spec) {
1380 		builtin_argv0 = NULL;
1381 		/* may not want to use LERROR here */
1382 		unwind(LERROR);
1383 	}
1384 }
1385 
1386 /*
1387  * Used by functions called by builtins and not:
1388  * identical to errorfx if first argument is nil,
1389  * like bi_errorf storing the errorlevel into it otherwise
1390  */
1391 void
maybe_errorf(int * ep,int rc,const char * fmt,...)1392 maybe_errorf(int *ep, int rc, const char *fmt, ...)
1393 {
1394 	va_list va;
1395 
1396 	/* debugging: note that stdout not valid */
1397 	shl_stdout_ok = false;
1398 
1399 	exstat = rc;
1400 
1401 	va_start(va, fmt);
1402 	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1403 	    (ep ? VWARNINGF_BUILTIN : 0), fmt, va);
1404 	va_end(va);
1405 
1406 	if (!ep)
1407 		goto and_out;
1408 	*ep = rc;
1409 
1410 	/* POSIX special builtins cause non-interactive shells to exit */
1411 	if (builtin_spec) {
1412 		builtin_argv0 = NULL;
1413 		/* may not want to use LERROR here */
1414  and_out:
1415 		unwind(LERROR);
1416 	}
1417 }
1418 
1419 /* Called when something that shouldn't happen does */
1420 void
internal_errorf(const char * fmt,...)1421 internal_errorf(const char *fmt, ...)
1422 {
1423 	va_list va;
1424 
1425 	va_start(va, fmt);
1426 	vwarningf(VWARNINGF_INTERNAL, fmt, va);
1427 	va_end(va);
1428 	unwind(LERROR);
1429 }
1430 
1431 void
internal_warningf(const char * fmt,...)1432 internal_warningf(const char *fmt, ...)
1433 {
1434 	va_list va;
1435 
1436 	va_start(va, fmt);
1437 	vwarningf(VWARNINGF_INTERNAL, fmt, va);
1438 	va_end(va);
1439 }
1440 
1441 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
1442 void
error_prefix(bool fileline)1443 error_prefix(bool fileline)
1444 {
1445 	/* Avoid foo: foo[2]: ... */
1446 	if (!fileline || !source || !source->file ||
1447 	    strcmp(source->file, kshname) != 0)
1448 		shf_fprintf(shl_out, Tf_sD_, kshname +
1449 		    (*kshname == '-' ? 1 : 0));
1450 	if (fileline && source && source->file != NULL) {
1451 		shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1452 		    (unsigned long)(source->errline ?
1453 		    source->errline : source->line));
1454 		source->errline = 0;
1455 	}
1456 }
1457 
1458 /* printf to shl_out (stderr) with flush */
1459 void
shellf(const char * fmt,...)1460 shellf(const char *fmt, ...)
1461 {
1462 	va_list va;
1463 
1464 	if (!initio_done)
1465 		/* shl_out may not be set up yet... */
1466 		return;
1467 	va_start(va, fmt);
1468 	shf_vfprintf(shl_out, fmt, va);
1469 	va_end(va);
1470 	shf_flush(shl_out);
1471 }
1472 
1473 /* printf to shl_stdout (stdout) */
1474 void
shprintf(const char * fmt,...)1475 shprintf(const char *fmt, ...)
1476 {
1477 	va_list va;
1478 
1479 	if (!shl_stdout_ok)
1480 		internal_errorf("shl_stdout not valid");
1481 	va_start(va, fmt);
1482 	shf_vfprintf(shl_stdout, fmt, va);
1483 	va_end(va);
1484 }
1485 
1486 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1487 int
can_seek(int fd)1488 can_seek(int fd)
1489 {
1490 	struct stat statb;
1491 
1492 	return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1493 	    SHF_UNBUF : 0);
1494 }
1495 
1496 #ifdef DF
1497 int shl_dbg_fd;
1498 #define NSHF_IOB 4
1499 #else
1500 #define NSHF_IOB 3
1501 #endif
1502 struct shf shf_iob[NSHF_IOB];
1503 
1504 void
initio(void)1505 initio(void)
1506 {
1507 #ifdef DF
1508 	const char *lfp;
1509 #endif
1510 
1511 	/* force buffer allocation */
1512 	shf_fdopen(1, SHF_WR, shl_stdout);
1513 	shf_fdopen(2, SHF_WR, shl_out);
1514 	shf_fdopen(2, SHF_WR, shl_xtrace);
1515 #ifdef DF
1516 	if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
1517 		if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
1518 			errorf("can't get home directory");
1519 		strpathx(lfp, lfp, "mksh-dbg.txt", 1);
1520 	}
1521 
1522 	if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
1523 		errorf("can't open debug output file %s", lfp);
1524 	if (shl_dbg_fd < FDBASE) {
1525 		int nfd;
1526 
1527 		nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1528 		close(shl_dbg_fd);
1529 		if ((shl_dbg_fd = nfd) == -1)
1530 			errorf("can't dup debug output file");
1531 	}
1532 	fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1533 	shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1534 	DF("=== open ===");
1535 #endif
1536 	initio_done = true;
1537 }
1538 
1539 /* A dup2() with error checking */
1540 int
ksh_dup2(int ofd,int nfd,bool errok)1541 ksh_dup2(int ofd, int nfd, bool errok)
1542 {
1543 	int rv;
1544 
1545 	if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1546 		errorf(Ttoo_many_files);
1547 
1548 #ifdef __ultrix
1549 	/*XXX imake style */
1550 	if (rv >= 0)
1551 		fcntl(nfd, F_SETFD, 0);
1552 #endif
1553 
1554 	return (rv);
1555 }
1556 
1557 /*
1558  * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1559  * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
1560  */
1561 short
savefd(int fd)1562 savefd(int fd)
1563 {
1564 	int nfd = fd;
1565 
1566 	if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1567 	    (errno == EBADF || errno == EPERM))
1568 		return (-1);
1569 	if (nfd < 0 || nfd > SHRT_MAX)
1570 		errorf(Ttoo_many_files);
1571 	fcntl(nfd, F_SETFD, FD_CLOEXEC);
1572 	return ((short)nfd);
1573 }
1574 
1575 void
restfd(int fd,int ofd)1576 restfd(int fd, int ofd)
1577 {
1578 	if (fd == 2)
1579 		shf_flush(&shf_iob[/* fd */ 2]);
1580 	if (ofd < 0)
1581 		/* original fd closed */
1582 		close(fd);
1583 	else if (fd != ofd) {
1584 		/*XXX: what to do if this dup fails? */
1585 		ksh_dup2(ofd, fd, true);
1586 		close(ofd);
1587 	}
1588 }
1589 
1590 void
openpipe(int * pv)1591 openpipe(int *pv)
1592 {
1593 	int lpv[2];
1594 
1595 	if (pipe(lpv) < 0)
1596 		errorf("can't create pipe - try again");
1597 	pv[0] = savefd(lpv[0]);
1598 	if (pv[0] != lpv[0])
1599 		close(lpv[0]);
1600 	pv[1] = savefd(lpv[1]);
1601 	if (pv[1] != lpv[1])
1602 		close(lpv[1]);
1603 #ifdef __OS2__
1604 	setmode(pv[0], O_BINARY);
1605 	setmode(pv[1], O_BINARY);
1606 #endif
1607 }
1608 
1609 void
closepipe(int * pv)1610 closepipe(int *pv)
1611 {
1612 	close(pv[0]);
1613 	close(pv[1]);
1614 }
1615 
1616 /*
1617  * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1618  * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1619  */
1620 int
check_fd(const char * name,int mode,const char ** emsgp)1621 check_fd(const char *name, int mode, const char **emsgp)
1622 {
1623 	int fd, fl;
1624 
1625 	if (!name[0] || name[1])
1626 		goto illegal_fd_name;
1627 	if (name[0] == 'p')
1628 		return (coproc_getfd(mode, emsgp));
1629 	if (!ctype(name[0], C_DIGIT)) {
1630  illegal_fd_name:
1631 		if (emsgp)
1632 			*emsgp = "illegal file descriptor name";
1633 		return (-1);
1634 	}
1635 
1636 	if ((fl = fcntl((fd = ksh_numdig(name[0])), F_GETFL, 0)) < 0) {
1637 		if (emsgp)
1638 			*emsgp = "bad file descriptor";
1639 		return (-1);
1640 	}
1641 	fl &= O_ACCMODE;
1642 	/*
1643 	 * X_OK is a kludge to disable this check for dups (x<&1):
1644 	 * historical shells never did this check (XXX don't know what
1645 	 * POSIX has to say).
1646 	 */
1647 	if (!(mode & X_OK) && fl != O_RDWR && (
1648 	    ((mode & R_OK) && fl != O_RDONLY) ||
1649 	    ((mode & W_OK) && fl != O_WRONLY))) {
1650 		if (emsgp)
1651 			*emsgp = (fl == O_WRONLY) ?
1652 			    "fd not open for reading" :
1653 			    "fd not open for writing";
1654 		return (-1);
1655 	}
1656 	return (fd);
1657 }
1658 
1659 /* Called once from main */
1660 void
coproc_init(void)1661 coproc_init(void)
1662 {
1663 	coproc.read = coproc.readw = coproc.write = -1;
1664 	coproc.njobs = 0;
1665 	coproc.id = 0;
1666 }
1667 
1668 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1669 void
coproc_read_close(int fd)1670 coproc_read_close(int fd)
1671 {
1672 	if (coproc.read >= 0 && fd == coproc.read) {
1673 		coproc_readw_close(fd);
1674 		close(coproc.read);
1675 		coproc.read = -1;
1676 	}
1677 }
1678 
1679 /*
1680  * Called by c_read() and by iosetup() to close the other side of the
1681  * read pipe, so reads will actually terminate.
1682  */
1683 void
coproc_readw_close(int fd)1684 coproc_readw_close(int fd)
1685 {
1686 	if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1687 		close(coproc.readw);
1688 		coproc.readw = -1;
1689 	}
1690 }
1691 
1692 /*
1693  * Called by c_print when a write to a fd fails with EPIPE and by iosetup
1694  * when co-process input is dup'd
1695  */
1696 void
coproc_write_close(int fd)1697 coproc_write_close(int fd)
1698 {
1699 	if (coproc.write >= 0 && fd == coproc.write) {
1700 		close(coproc.write);
1701 		coproc.write = -1;
1702 	}
1703 }
1704 
1705 /*
1706  * Called to check for existence of/value of the co-process file descriptor.
1707  * (Used by check_fd() and by c_read/c_print to deal with -p option).
1708  */
1709 int
coproc_getfd(int mode,const char ** emsgp)1710 coproc_getfd(int mode, const char **emsgp)
1711 {
1712 	int fd = (mode & R_OK) ? coproc.read : coproc.write;
1713 
1714 	if (fd >= 0)
1715 		return (fd);
1716 	if (emsgp)
1717 		*emsgp = "no coprocess";
1718 	return (-1);
1719 }
1720 
1721 /*
1722  * called to close file descriptors related to the coprocess (if any)
1723  * Should be called with SIGCHLD blocked.
1724  */
1725 void
coproc_cleanup(int reuse)1726 coproc_cleanup(int reuse)
1727 {
1728 	/* This to allow co-processes to share output pipe */
1729 	if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1730 		if (coproc.read >= 0) {
1731 			close(coproc.read);
1732 			coproc.read = -1;
1733 		}
1734 		if (coproc.readw >= 0) {
1735 			close(coproc.readw);
1736 			coproc.readw = -1;
1737 		}
1738 	}
1739 	if (coproc.write >= 0) {
1740 		close(coproc.write);
1741 		coproc.write = -1;
1742 	}
1743 }
1744 
1745 struct temp *
maketemp(Area * ap,Temp_type type,struct temp ** tlist)1746 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1747 {
1748 	char *cp;
1749 	size_t len;
1750 	int i, j;
1751 	struct temp *tp;
1752 	const char *dir;
1753 	struct stat sb;
1754 
1755 	dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1756 	/* add "/shXXXXXX.tmp" plus NUL */
1757 	len = strlen(dir);
1758 	checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1759 	tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
1760 
1761 	tp->shf = NULL;
1762 	tp->pid = procpid;
1763 	tp->type = type;
1764 
1765 	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1766 		tp->tffn[0] = '\0';
1767 		goto maketemp_out;
1768 	}
1769 
1770 	cp = (void *)tp;
1771 	cp += offsetof(struct temp, tffn[0]);
1772 	memcpy(cp, dir, len);
1773 	cp += len;
1774 	memcpy(cp, "/shXXXXXX.tmp", 14);
1775 	/* point to the first of six Xes */
1776 	cp += 3;
1777 
1778 	/* cyclically attempt to open a temporary file */
1779 	do {
1780 		/* generate random part of filename */
1781 		len = 0;
1782 		do {
1783 			cp[len++] = digits_lc[rndget() % 36];
1784 		} while (len < 6);
1785 
1786 		/* check if this one works */
1787 		if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1788 		    0600)) < 0 && errno != EEXIST)
1789 			goto maketemp_out;
1790 	} while (i < 0);
1791 
1792 	if (type == TT_FUNSUB) {
1793 		/* map us high and mark as close-on-exec */
1794 		if ((j = savefd(i)) != i) {
1795 			close(i);
1796 			i = j;
1797 		}
1798 
1799 		/* operation mode for the shf */
1800 		j = SHF_RD;
1801 	} else
1802 		j = SHF_WR;
1803 
1804 	/* shf_fdopen cannot fail, so no fd leak */
1805 	tp->shf = shf_fdopen(i, j, NULL);
1806 
1807  maketemp_out:
1808 	tp->next = *tlist;
1809 	*tlist = tp;
1810 	return (tp);
1811 }
1812 
1813 /*
1814  * We use a similar collision resolution algorithm as Python 2.5.4
1815  * but with a slightly tweaked implementation written from scratch.
1816  */
1817 
1818 #define	INIT_TBLSHIFT	3	/* initial table shift (2^3 = 8) */
1819 #define PERTURB_SHIFT	5	/* see Python 2.5.4 Objects/dictobject.c */
1820 
1821 static void tgrow(struct table *);
1822 static int tnamecmp(const void *, const void *);
1823 
1824 static void
tgrow(struct table * tp)1825 tgrow(struct table *tp)
1826 {
1827 	size_t i, j, osize, mask, perturb;
1828 	struct tbl *tblp, **pp;
1829 	struct tbl **ntblp, **otblp = tp->tbls;
1830 
1831 	if (tp->tshift > 29)
1832 		internal_errorf("hash table size limit reached");
1833 
1834 	/* calculate old size, new shift and new size */
1835 	osize = (size_t)1 << (tp->tshift++);
1836 	i = osize << 1;
1837 
1838 	ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1839 	/* multiplication cannot overflow: alloc2 checked that */
1840 	memset(ntblp, 0, i * sizeof(struct tbl *));
1841 
1842 	/* table can get very full when reaching its size limit */
1843 	tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1844 	    /* but otherwise, only 75% */
1845 	    ((i * 3) / 4);
1846 	tp->tbls = ntblp;
1847 	if (otblp == NULL)
1848 		return;
1849 
1850 	mask = i - 1;
1851 	for (i = 0; i < osize; i++)
1852 		if ((tblp = otblp[i]) != NULL) {
1853 			if ((tblp->flag & DEFINED)) {
1854 				/* search for free hash table slot */
1855 				j = perturb = tblp->ua.hval;
1856 				goto find_first_empty_slot;
1857  find_next_empty_slot:
1858 				j = (j << 2) + j + perturb + 1;
1859 				perturb >>= PERTURB_SHIFT;
1860  find_first_empty_slot:
1861 				pp = &ntblp[j & mask];
1862 				if (*pp != NULL)
1863 					goto find_next_empty_slot;
1864 				/* found an empty hash table slot */
1865 				*pp = tblp;
1866 				tp->nfree--;
1867 			} else if (!(tblp->flag & FINUSE)) {
1868 				afree(tblp, tp->areap);
1869 			}
1870 		}
1871 	afree(otblp, tp->areap);
1872 }
1873 
1874 void
ktinit(Area * ap,struct table * tp,uint8_t initshift)1875 ktinit(Area *ap, struct table *tp, uint8_t initshift)
1876 {
1877 	tp->areap = ap;
1878 	tp->tbls = NULL;
1879 	tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1880 	    initshift : INIT_TBLSHIFT) - 1;
1881 	tgrow(tp);
1882 }
1883 
1884 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1885 struct tbl *
ktscan(struct table * tp,const char * name,uint32_t h,struct tbl *** ppp)1886 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1887 {
1888 	size_t j, perturb, mask;
1889 	struct tbl **pp, *p;
1890 
1891 	mask = ((size_t)1 << (tp->tshift)) - 1;
1892 	/* search for hash table slot matching name */
1893 	j = perturb = h;
1894 	goto find_first_slot;
1895  find_next_slot:
1896 	j = (j << 2) + j + perturb + 1;
1897 	perturb >>= PERTURB_SHIFT;
1898  find_first_slot:
1899 	pp = &tp->tbls[j & mask];
1900 	if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1901 	    strcmp(p->name, name)))
1902 		goto find_next_slot;
1903 	/* p == NULL if not found, correct found entry otherwise */
1904 	if (ppp)
1905 		*ppp = pp;
1906 	return (p);
1907 }
1908 
1909 /* table, name (key) to enter, hash(n) */
1910 struct tbl *
ktenter(struct table * tp,const char * n,uint32_t h)1911 ktenter(struct table *tp, const char *n, uint32_t h)
1912 {
1913 	struct tbl **pp, *p;
1914 	size_t len;
1915 
1916  Search:
1917 	if ((p = ktscan(tp, n, h, &pp)))
1918 		return (p);
1919 
1920 	if (tp->nfree == 0) {
1921 		/* too full */
1922 		tgrow(tp);
1923 		goto Search;
1924 	}
1925 
1926 	/* create new tbl entry */
1927 	len = strlen(n);
1928 	checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1929 	p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
1930 	p->flag = 0;
1931 	p->type = 0;
1932 	p->areap = tp->areap;
1933 	p->ua.hval = h;
1934 	p->u2.field = 0;
1935 	p->u.array = NULL;
1936 	memcpy(p->name, n, len);
1937 
1938 	/* enter in tp->tbls */
1939 	tp->nfree--;
1940 	*pp = p;
1941 	return (p);
1942 }
1943 
1944 void
ktwalk(struct tstate * ts,struct table * tp)1945 ktwalk(struct tstate *ts, struct table *tp)
1946 {
1947 	ts->left = (size_t)1 << (tp->tshift);
1948 	ts->next = tp->tbls;
1949 }
1950 
1951 struct tbl *
ktnext(struct tstate * ts)1952 ktnext(struct tstate *ts)
1953 {
1954 	while (--ts->left >= 0) {
1955 		struct tbl *p = *ts->next++;
1956 		if (p != NULL && (p->flag & DEFINED))
1957 			return (p);
1958 	}
1959 	return (NULL);
1960 }
1961 
1962 static int
tnamecmp(const void * p1,const void * p2)1963 tnamecmp(const void *p1, const void *p2)
1964 {
1965 	const struct tbl *a = *((const struct tbl * const *)p1);
1966 	const struct tbl *b = *((const struct tbl * const *)p2);
1967 
1968 	return (ascstrcmp(a->name, b->name));
1969 }
1970 
1971 struct tbl **
ktsort(struct table * tp)1972 ktsort(struct table *tp)
1973 {
1974 	size_t i;
1975 	struct tbl **p, **sp, **dp;
1976 
1977 	/*
1978 	 * since the table is never entirely full, no need to reserve
1979 	 * additional space for the trailing NULL appended below
1980 	 */
1981 	i = (size_t)1 << (tp->tshift);
1982 	p = alloc2(i, sizeof(struct tbl *), ATEMP);
1983 	sp = tp->tbls;		/* source */
1984 	dp = p;			/* dest */
1985 	while (i--)
1986 		if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1987 		    ((*dp)->flag & ARRAY)))
1988 			dp++;
1989 	qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
1990 	p[i] = NULL;
1991 	return (p);
1992 }
1993 
1994 #ifdef SIGWINCH
1995 static void
x_sigwinch(int sig MKSH_A_UNUSED)1996 x_sigwinch(int sig MKSH_A_UNUSED)
1997 {
1998 	/* this runs inside interrupt context, with errno saved */
1999 
2000 	got_winch = 1;
2001 }
2002 #endif
2003 
2004 #ifdef DF
2005 void
DF(const char * fmt,...)2006 DF(const char *fmt, ...)
2007 {
2008 	va_list args;
2009 	struct timeval tv;
2010 	mirtime_mjd mjd;
2011 
2012 	mksh_lockfd(shl_dbg_fd);
2013 	mksh_TIME(tv);
2014 	timet2mjd(&mjd, tv.tv_sec);
2015 	shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
2016 	    (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
2017 	    (unsigned)mjd.sec % 60, (unsigned)getpid(),
2018 	    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
2019 	va_start(args, fmt);
2020 	shf_vfprintf(shl_dbg, fmt, args);
2021 	va_end(args);
2022 	shf_putc('\n', shl_dbg);
2023 	shf_flush(shl_dbg);
2024 	mksh_unlkfd(shl_dbg_fd);
2025 }
2026 #endif
2027 
2028 void
x_mkraw(int fd,mksh_ttyst * ocb,bool forread)2029 x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
2030 {
2031 	mksh_ttyst cb;
2032 
2033 	if (ocb)
2034 		mksh_tcget(fd, ocb);
2035 	else
2036 		ocb = &tty_state;
2037 
2038 	cb = *ocb;
2039 	if (forread) {
2040 		cb.c_iflag &= ~(ISTRIP);
2041 		cb.c_lflag &= ~(ICANON) | ECHO;
2042 	} else {
2043 		cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
2044 		cb.c_lflag &= ~(ISIG | ICANON | ECHO);
2045 	}
2046 #if defined(VLNEXT) && defined(_POSIX_VDISABLE)
2047 	/* OSF/1 processes lnext when ~icanon */
2048 	cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
2049 #endif
2050 	/* SunOS 4.1.x and OSF/1 process discard(flush) when ~icanon */
2051 #if defined(VDISCARD) && defined(_POSIX_VDISABLE)
2052 	cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
2053 #endif
2054 	cb.c_cc[VTIME] = 0;
2055 	cb.c_cc[VMIN] = 1;
2056 
2057 	mksh_tcset(fd, &cb);
2058 }
2059 
2060 #ifdef MKSH_ENVDIR
2061 static void
init_environ(void)2062 init_environ(void)
2063 {
2064 	char *xp;
2065 	ssize_t n;
2066 	XString xs;
2067 	struct shf *shf;
2068 	DIR *dirp;
2069 	struct dirent *dent;
2070 
2071 	if ((dirp = opendir(MKSH_ENVDIR)) == NULL) {
2072 		warningf(false, "cannot read environment from %s: %s",
2073 		    MKSH_ENVDIR, cstrerror(errno));
2074 		return;
2075 	}
2076 	XinitN(xs, 256, ATEMP);
2077  read_envfile:
2078 	errno = 0;
2079 	if ((dent = readdir(dirp)) != NULL) {
2080 		if (skip_varname(dent->d_name, true)[0] == '\0') {
2081 			strpathx(xp, MKSH_ENVDIR, dent->d_name, 1);
2082 			if (!(shf = shf_open(xp, O_RDONLY, 0, 0))) {
2083 				warningf(false,
2084 				    "cannot read environment %s from %s: %s",
2085 				    dent->d_name, MKSH_ENVDIR,
2086 				    cstrerror(errno));
2087 				goto read_envfile;
2088 			}
2089 			afree(xp, ATEMP);
2090 			n = strlen(dent->d_name);
2091 			xp = Xstring(xs, xp);
2092 			XcheckN(xs, xp, n + 32);
2093 			memcpy(xp, dent->d_name, n);
2094 			xp += n;
2095 			*xp++ = '=';
2096 			while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
2097 				xp += n;
2098 				if (Xnleft(xs, xp) <= 0)
2099 					XcheckN(xs, xp, Xlength(xs, xp));
2100 			}
2101 			if (n < 0) {
2102 				warningf(false,
2103 				    "cannot read environment %s from %s: %s",
2104 				    dent->d_name, MKSH_ENVDIR,
2105 				    cstrerror(shf_errno(shf)));
2106 			} else {
2107 				*xp = '\0';
2108 				xp = Xstring(xs, xp);
2109 				rndpush(xp);
2110 				typeset(xp, IMPORT | EXPORT, 0, 0, 0);
2111 			}
2112 			shf_close(shf);
2113 		}
2114 		goto read_envfile;
2115 	} else if (errno)
2116 		warningf(false, "cannot read environment from %s: %s",
2117 		    MKSH_ENVDIR, cstrerror(errno));
2118 	closedir(dirp);
2119 	Xfree(xs, xp);
2120 }
2121 #else
2122 extern char **environ;
2123 
2124 static void
init_environ(void)2125 init_environ(void)
2126 {
2127 	const char **wp;
2128 
2129 	if (environ == NULL)
2130 		return;
2131 
2132 	wp = (const char **)environ;
2133 	while (*wp != NULL) {
2134 		rndpush(*wp);
2135 		typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
2136 		++wp;
2137 	}
2138 }
2139 #endif
2140 
2141 #ifdef MKSH_EARLY_LOCALE_TRACKING
2142 void
recheck_ctype(void)2143 recheck_ctype(void)
2144 {
2145 	const char *ccp;
2146 	uint8_t old_utfmode = UTFMODE;
2147 
2148 	ccp = str_val(global("LC_ALL"));
2149 	if (ccp == null)
2150 		ccp = str_val(global("LC_CTYPE"));
2151 	if (ccp == null)
2152 		ccp = str_val(global("LANG"));
2153 	UTFMODE = isuc(ccp);
2154 #if HAVE_SETLOCALE_CTYPE
2155 	ccp = setlocale(LC_CTYPE, ccp);
2156 #if HAVE_LANGINFO_CODESET
2157 	if (!isuc(ccp))
2158 		ccp = nl_langinfo(CODESET);
2159 #endif
2160 	if (isuc(ccp))
2161 		UTFMODE = 1;
2162 #endif
2163 
2164 	if (Flag(FPOSIX) && UTFMODE && !old_utfmode)
2165 		warningf(true, "early locale tracking enabled UTF-8 mode while in POSIX mode, you are now noncompliant");
2166 }
2167 #endif
2168