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