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