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