1 /*	$OpenBSD: exec.c,v 1.52 2015/09/10 22:48:58 nicm Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
6  *		 2019, 2020
7  *	mirabilos <m@mirbsd.org>
8  *
9  * Provided that these terms and disclaimer and all copyright notices
10  * are retained or reproduced in an accompanying document, permission
11  * is granted to deal in this work without restriction, including un-
12  * limited rights to use, publicly perform, distribute, sell, modify,
13  * merge, give away, or sublicence.
14  *
15  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
16  * the utmost extent permitted by applicable law, neither express nor
17  * implied; without malicious intent or gross negligence. In no event
18  * may a licensor, author or contributor be held liable for indirect,
19  * direct, other damage, loss, or other issues arising in any way out
20  * of dealing in the work, even if advised of the possibility of such
21  * damage or existence of a defect, except proven that it results out
22  * of said person's immediate fault when using the work as intended.
23  */
24 
25 #include "sh.h"
26 
27 __RCSID("$MirOS: src/bin/mksh/exec.c,v 1.223 2020/04/07 23:14:41 tg Exp $");
28 
29 #ifndef MKSH_DEFAULT_EXECSHELL
30 #define MKSH_DEFAULT_EXECSHELL	MKSH_UNIXROOT "/bin/sh"
31 #endif
32 
33 static int comexec(struct op *, struct tbl * volatile, const char **,
34     int volatile, volatile int *);
35 static void scriptexec(struct op *, const char **) MKSH_A_NORETURN;
36 static int call_builtin(struct tbl *, const char **, const char *, bool);
37 static int iosetup(struct ioword *, struct tbl *);
38 static const char *do_selectargs(const char **, bool);
39 static Test_op dbteste_isa(Test_env *, Test_meta);
40 static const char *dbteste_getopnd(Test_env *, Test_op, bool);
41 static void dbteste_error(Test_env *, int, const char *);
42 /* XXX: horrible kludge to fit within the framework */
43 static void plain_fmt_entry(char *, size_t, unsigned int, const void *);
44 static void select_fmt_entry(char *, size_t, unsigned int, const void *);
45 
46 /*
47  * execute command tree
48  */
49 int
execute(struct op * volatile t,volatile int flags,volatile int * volatile xerrok)50 execute(struct op * volatile t,
51     /* if XEXEC don't fork */
52     volatile int flags,
53     volatile int * volatile xerrok)
54 {
55 	int i;
56 	volatile int rv = 0, dummy = 0;
57 	int pv[2];
58 	const char ** volatile ap = NULL;
59 	char ** volatile up;
60 	const char *s, *ccp;
61 	struct ioword **iowp;
62 	struct tbl *tp = NULL;
63 
64 	if (t == NULL)
65 		return (0);
66 
67 	/* Caller doesn't care if XERROK should propagate. */
68 	if (xerrok == NULL)
69 		xerrok = &dummy;
70 
71 	if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
72 		/* run in sub-process */
73 		return (exchild(t, flags & ~XTIME, xerrok, -1));
74 
75 	newenv(E_EXEC);
76 	if (trap)
77 		runtraps(0);
78 
79 	/* we want to run an executable, do some variance checks */
80 	if (t->type == TCOM) {
81 		/*
82 		 * Clear subst_exstat before argument expansion. Used by
83 		 * null commands (see comexec() and c_eval()) and by c_set().
84 		 */
85 		subst_exstat = 0;
86 
87 		/* for $LINENO */
88 		current_lineno = t->lineno;
89 
90 		/* check if this is 'var=<<EOF' */
91 		if (
92 		    /* we have zero arguments, i.e. no program to run */
93 		    t->args[0] == NULL &&
94 		    /* we have exactly one variable assignment */
95 		    t->vars[0] != NULL && t->vars[1] == NULL &&
96 		    /* we have exactly one I/O redirection */
97 		    t->ioact != NULL && t->ioact[0] != NULL &&
98 		    t->ioact[1] == NULL &&
99 		    /* of type "here document" (or "here string") */
100 		    (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
101 		    /* the variable assignment begins with a valid varname */
102 		    (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
103 		    /* and has no right-hand side (i.e. "varname=") */
104 		    ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
105 		    /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
106 		    ccp[3] == '=' && ccp[4] == EOS))) {
107 			char *cp, *dp;
108 
109 			if ((rv = herein(t->ioact[0], &cp) /*? 1 : 0*/))
110 				cp = NULL;
111 			strdup2x(dp, evalstr(t->vars[0], DOASNTILDE | DOSCALAR),
112 			    rv ? null : cp);
113 			typeset(dp, Flag(FEXPORT) ? EXPORT : 0, 0, 0, 0);
114 			/* free the expanded value */
115 			afree(cp, APERM);
116 			afree(dp, ATEMP);
117 			goto Break;
118 		}
119 
120 		/*
121 		 * POSIX says expand command words first, then redirections,
122 		 * and assignments last..
123 		 */
124 		up = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
125 		if (flags & XTIME)
126 			/* Allow option parsing (bizarre, but POSIX) */
127 			timex_hook(t, &up);
128 		ap = (const char **)up;
129 		if (ap[0])
130 			tp = findcom(ap[0], FC_BI | FC_FUNC);
131 	}
132 	flags &= ~XTIME;
133 
134 	if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
135 		e->savefd = alloc2(NUFILE, sizeof(short), ATEMP);
136 		/* initialise to not redirected */
137 		memset(e->savefd, 0, NUFILE * sizeof(short));
138 	}
139 
140 	/* mark for replacement later (unless TPIPE) */
141 	vp_pipest->flag |= INT_L;
142 
143 	/* do redirection, to be restored in quitenv() */
144 	if (t->ioact != NULL)
145 		for (iowp = t->ioact; *iowp != NULL; iowp++) {
146 			if (iosetup(*iowp, tp) < 0) {
147 				exstat = rv = 1;
148 				/*
149 				 * Redirection failures for special commands
150 				 * cause (non-interactive) shell to exit.
151 				 */
152 				if (tp && tp->type == CSHELL &&
153 				    (tp->flag & SPEC_BI))
154 					errorfz();
155 				/* Deal with FERREXIT, quitenv(), etc. */
156 				goto Break;
157 			}
158 		}
159 
160 	switch (t->type) {
161 	case TCOM:
162 		rv = comexec(t, tp, (const char **)ap, flags, xerrok);
163 		break;
164 
165 	case TPAREN:
166 		rv = execute(t->left, flags | XFORK, xerrok);
167 		break;
168 
169 	case TPIPE:
170 		flags |= XFORK;
171 		flags &= ~XEXEC;
172 		e->savefd[0] = savefd(0);
173 		e->savefd[1] = savefd(1);
174 		while (t->type == TPIPE) {
175 			openpipe(pv);
176 			/* stdout of curr */
177 			ksh_dup2(pv[1], 1, false);
178 			/**
179 			 * Let exchild() close pv[0] in child
180 			 * (if this isn't done, commands like
181 			 *	(: ; cat /etc/termcap) | sleep 1
182 			 * will hang forever).
183 			 */
184 			exchild(t->left, flags | XPIPEO | XCCLOSE,
185 			    NULL, pv[0]);
186 			/* stdin of next */
187 			ksh_dup2(pv[0], 0, false);
188 			closepipe(pv);
189 			flags |= XPIPEI;
190 			t = t->right;
191 		}
192 		/* stdout of last */
193 		restfd(1, e->savefd[1]);
194 		/* no need to re-restore this */
195 		e->savefd[1] = 0;
196 		/* Let exchild() close 0 in parent, after fork, before wait */
197 		i = exchild(t, flags | XPCLOSE | XPIPEST, xerrok, 0);
198 		if (!(flags&XBGND) && !(flags&XXCOM))
199 			rv = i;
200 		break;
201 
202 	case TLIST:
203 		while (t->type == TLIST) {
204 			execute(t->left, flags & XERROK, NULL);
205 			t = t->right;
206 		}
207 		rv = execute(t, flags & XERROK, xerrok);
208 		break;
209 
210 	case TCOPROC: {
211 #ifndef MKSH_NOPROSPECTOFWORK
212 		sigset_t omask;
213 
214 		/*
215 		 * Block sigchild as we are using things changed in the
216 		 * signal handler
217 		 */
218 		sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
219 		e->type = E_ERRH;
220 		if ((i = kshsetjmp(e->jbuf))) {
221 			sigprocmask(SIG_SETMASK, &omask, NULL);
222 			quitenv(NULL);
223 			unwind(i);
224 			/* NOTREACHED */
225 		}
226 #endif
227 		/* Already have a (live) co-process? */
228 		if (coproc.job && coproc.write >= 0)
229 			errorf("coprocess already exists");
230 
231 		/* Can we re-use the existing co-process pipe? */
232 		coproc_cleanup(true);
233 
234 		/* do this before opening pipes, in case these fail */
235 		e->savefd[0] = savefd(0);
236 		e->savefd[1] = savefd(1);
237 
238 		openpipe(pv);
239 		if (pv[0] != 0) {
240 			ksh_dup2(pv[0], 0, false);
241 			close(pv[0]);
242 		}
243 		coproc.write = pv[1];
244 		coproc.job = NULL;
245 
246 		if (coproc.readw >= 0)
247 			ksh_dup2(coproc.readw, 1, false);
248 		else {
249 			openpipe(pv);
250 			coproc.read = pv[0];
251 			ksh_dup2(pv[1], 1, false);
252 			/* closed before first read */
253 			coproc.readw = pv[1];
254 			coproc.njobs = 0;
255 			/* create new coprocess id */
256 			++coproc.id;
257 		}
258 #ifndef MKSH_NOPROSPECTOFWORK
259 		sigprocmask(SIG_SETMASK, &omask, NULL);
260 		/* no more need for error handler */
261 		e->type = E_EXEC;
262 #endif
263 
264 		/*
265 		 * exchild() closes coproc.* in child after fork,
266 		 * will also increment coproc.njobs when the
267 		 * job is actually created.
268 		 */
269 		flags &= ~XEXEC;
270 		exchild(t->left, flags | XBGND | XFORK | XCOPROC | XCCLOSE,
271 		    NULL, coproc.readw);
272 		break;
273 	}
274 
275 	case TASYNC:
276 		/*
277 		 * XXX non-optimal, I think - "(foo &)", forks for (),
278 		 * forks again for async... parent should optimise
279 		 * this to "foo &"...
280 		 */
281 		rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK, xerrok);
282 		break;
283 
284 	case TOR:
285 	case TAND:
286 		rv = execute(t->left, XERROK, NULL);
287 		if ((rv == 0) == (t->type == TAND))
288 			rv = execute(t->right, flags & XERROK, xerrok);
289 		else {
290 			flags |= XERROK;
291 			if (xerrok)
292 				*xerrok = 1;
293 		}
294 		break;
295 
296 	case TBANG:
297 		rv = !execute(t->right, XERROK, xerrok);
298 		flags |= XERROK;
299 		if (xerrok)
300 			*xerrok = 1;
301 		break;
302 
303 	case TDBRACKET: {
304 		Test_env te;
305 
306 		te.flags = TEF_DBRACKET;
307 		te.pos.wp = t->args;
308 		te.isa = dbteste_isa;
309 		te.getopnd = dbteste_getopnd;
310 		te.eval = test_eval;
311 		te.error = dbteste_error;
312 
313 		rv = test_parse(&te);
314 		break;
315 	}
316 
317 	case TFOR:
318 	case TSELECT: {
319 		volatile bool is_first = true;
320 
321 		ap = (t->vars == NULL) ? e->loc->argv + 1 :
322 		    (const char **)eval((const char **)t->vars,
323 		    DOBLANK | DOGLOB | DOTILDE);
324 		e->type = E_LOOP;
325 		while ((i = kshsetjmp(e->jbuf))) {
326 			if ((e->flags&EF_BRKCONT_PASS) ||
327 			    (i != LBREAK && i != LCONTIN)) {
328 				quitenv(NULL);
329 				unwind(i);
330 			} else if (i == LBREAK) {
331 				rv = 0;
332 				goto Break;
333 			}
334 		}
335 		/* in case of a continue */
336 		rv = 0;
337 		if (t->type == TFOR) {
338 			while (*ap != NULL) {
339 				setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
340 				rv = execute(t->left, flags & XERROK, xerrok);
341 			}
342 		} else {
343  do_TSELECT:
344 			if ((ccp = do_selectargs(ap, is_first))) {
345 				is_first = false;
346 				setstr(global(t->str), ccp, KSH_UNWIND_ERROR);
347 				execute(t->left, flags & XERROK, xerrok);
348 				goto do_TSELECT;
349 			}
350 			rv = 1;
351 		}
352 		break;
353 	}
354 
355 	case TWHILE:
356 	case TUNTIL:
357 		e->type = E_LOOP;
358 		while ((i = kshsetjmp(e->jbuf))) {
359 			if ((e->flags&EF_BRKCONT_PASS) ||
360 			    (i != LBREAK && i != LCONTIN)) {
361 				quitenv(NULL);
362 				unwind(i);
363 			} else if (i == LBREAK) {
364 				rv = 0;
365 				goto Break;
366 			}
367 		}
368 		/* in case of a continue */
369 		rv = 0;
370 		while ((execute(t->left, XERROK, NULL) == 0) ==
371 		    (t->type == TWHILE))
372 			rv = execute(t->right, flags & XERROK, xerrok);
373 		break;
374 
375 	case TIF:
376 	case TELIF:
377 		if (t->right == NULL)
378 			/* should be error */
379 			break;
380 		rv = execute(execute(t->left, XERROK, NULL) == 0 ?
381 		    t->right->left : t->right->right, flags & XERROK, xerrok);
382 		break;
383 
384 	case TCASE:
385 		i = 0;
386 		ccp = evalstr(t->str, DOTILDE | DOSCALAR);
387 		for (t = t->left; t != NULL && t->type == TPAT; t = t->right) {
388 			for (ap = (const char **)t->vars; *ap; ap++) {
389 				if (i || ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
390 				    gmatchx(ccp, s, false))) {
391 					record_match(ccp);
392 					rv = execute(t->left, flags & XERROK,
393 					    xerrok);
394 					i = 0;
395 					switch (t->u.charflag) {
396 					case '&':
397 						i = 1;
398 						/* FALLTHROUGH */
399 					case '|':
400 						goto TCASE_next;
401 					}
402 					goto TCASE_out;
403 				}
404 			}
405 			i = 0;
406  TCASE_next:
407 			/* empty */;
408 		}
409  TCASE_out:
410 		break;
411 
412 	case TBRACE:
413 		rv = execute(t->left, flags & XERROK, xerrok);
414 		break;
415 
416 	case TFUNCT:
417 		rv = define(t->str, t);
418 		break;
419 
420 	case TTIME:
421 		/*
422 		 * Clear XEXEC so nested execute() call doesn't exit
423 		 * (allows "ls -l | time grep foo").
424 		 */
425 		rv = timex(t, flags & ~XEXEC, xerrok);
426 		break;
427 
428 	case TEXEC:
429 		/* an eval'd TCOM */
430 		up = makenv();
431 		restoresigs();
432 		cleanup_proc_env();
433 		/* I/O redirection cleanup to be done in child process */
434 		if (!Flag(FPOSIX) && !Flag(FSH) && t->left->ioact != NULL)
435 			for (iowp = t->left->ioact; *iowp != NULL; iowp++)
436 				if ((*iowp)->ioflag & IODUPSELF)
437 					fcntl((*iowp)->unit, F_SETFD, 0);
438 		/* try to execute */
439 		{
440 			union mksh_ccphack cargs;
441 
442 			cargs.ro = t->args;
443 			execve(t->str, cargs.rw, up);
444 			rv = errno;
445 		}
446 		if (rv == ENOEXEC)
447 			scriptexec(t, (const char **)up);
448 		else
449 			errorfx(126, Tf_sD_s, t->str, cstrerror(rv));
450 	}
451  Break:
452 	exstat = rv & 0xFF;
453 	if (vp_pipest->flag & INT_L) {
454 		unset(vp_pipest, 1);
455 		vp_pipest->flag = DEFINED | ISSET | INTEGER | RDONLY |
456 		    ARRAY | INT_U | INT_L;
457 		vp_pipest->val.i = rv;
458 	}
459 
460 	/* restores IO */
461 	quitenv(NULL);
462 	if ((flags&XEXEC))
463 		/* exit child */
464 		unwind(LEXIT);
465 	if (rv != 0 && !(flags & XERROK) &&
466 	    (xerrok == NULL || !*xerrok)) {
467 		trapsig(ksh_SIGERR);
468 		if (Flag(FERREXIT))
469 			unwind(LERREXT);
470 	}
471 	return (rv);
472 }
473 
474 /*
475  * execute simple command
476  */
477 
478 static int
comexec(struct op * t,struct tbl * volatile tp,const char ** ap,volatile int flags,volatile int * xerrok)479 comexec(struct op *t, struct tbl * volatile tp, const char **ap,
480     volatile int flags, volatile int *xerrok)
481 {
482 	int i;
483 	volatile int rv = 0;
484 	const char *cp;
485 	const char **lastp;
486 	/* Must be static (XXX but why?) */
487 	static struct op texec;
488 	int type_flags;
489 	bool resetspec;
490 	int fcflags = FC_BI | FC_FUNC | FC_PATH;
491 	struct block *l_expand, *l_assign;
492 	int optc;
493 	const char *exec_argv0 = NULL;
494 	bool exec_clrenv = false;
495 
496 	/* snag the last argument for $_ */
497 	if (Flag(FTALKING) && *(lastp = ap)) {
498 		/*
499 		 * XXX not the same as AT&T ksh, which only seems to set $_
500 		 * after a newline (but not in functions/dot scripts, but in
501 		 * interactive and script) - perhaps save last arg here and
502 		 * set it in shell()?.
503 		 */
504 		while (*++lastp)
505 			;
506 		/* setstr() can't fail here */
507 		setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
508 		    KSH_RETURN_ERROR);
509 	}
510 
511 	/**
512 	 * Deal with the shell builtins builtin, exec and command since
513 	 * they can be followed by other commands. This must be done before
514 	 * we know if we should create a local block which must be done
515 	 * before we can do a path search (in case the assignments change
516 	 * PATH).
517 	 * Odd cases:
518 	 *	FOO=bar exec >/dev/null		FOO is kept but not exported
519 	 *	FOO=bar exec foobar		FOO is exported
520 	 *	FOO=bar command exec >/dev/null	FOO is neither kept nor exported
521 	 *	FOO=bar command			FOO is neither kept nor exported
522 	 *	PATH=... foobar			use new PATH in foobar search
523 	 */
524 	resetspec = false;
525 	while (tp && tp->type == CSHELL) {
526 		/* undo effects of command */
527 		fcflags = FC_BI | FC_FUNC | FC_PATH;
528 		if (tp->val.f == c_builtin) {
529 			if ((cp = *++ap) == NULL ||
530 			    (!strcmp(cp, "--") && (cp = *++ap) == NULL)) {
531 				tp = NULL;
532 				break;
533 			}
534 			if ((tp = findcom(cp, FC_BI)) == NULL)
535 				errorf(Tf_sD_sD_s, Tbuiltin, cp, Tnot_found);
536 			if (tp->type == CSHELL && (tp->flag & LOW_BI))
537 				break;
538 			continue;
539 		} else if (tp->val.f == c_exec) {
540 			if (ap[1] == NULL)
541 				break;
542 			ksh_getopt_reset(&builtin_opt, GF_ERROR);
543 			while ((optc = ksh_getopt(ap, &builtin_opt, "a:c")) != -1)
544 				switch (optc) {
545 				case 'a':
546 					exec_argv0 = builtin_opt.optarg;
547 					break;
548 				case 'c':
549 					exec_clrenv = true;
550 					/* ensure we can actually do this */
551 					resetspec = true;
552 					break;
553 				default:
554 					rv = 2;
555 					goto Leave;
556 				}
557 			ap += builtin_opt.optind;
558 			flags |= XEXEC;
559 			/* POSuX demands ksh88-like behaviour here */
560 			if (Flag(FPOSIX))
561 				fcflags = FC_PATH;
562 		} else if (tp->val.f == c_command) {
563 			bool saw_p = false;
564 
565 			/*
566 			 * Ugly dealing with options in two places (here
567 			 * and in c_command(), but such is life)
568 			 */
569 			ksh_getopt_reset(&builtin_opt, 0);
570 			while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
571 				saw_p = true;
572 			if (optc != -1)
573 				/* command -vV or something */
574 				break;
575 			/* don't look for functions */
576 			fcflags = FC_BI | FC_PATH;
577 			if (saw_p) {
578 				if (Flag(FRESTRICTED)) {
579 					warningf(true, Tf_sD_s,
580 					    "command -p", "restricted");
581 					rv = 1;
582 					goto Leave;
583 				}
584 				fcflags |= FC_DEFPATH;
585 			}
586 			ap += builtin_opt.optind;
587 			/*
588 			 * POSIX says special builtins lose their status
589 			 * if accessed using command.
590 			 */
591 			resetspec = true;
592 			if (!ap[0]) {
593 				/* ensure command with no args exits with 0 */
594 				subst_exstat = 0;
595 				break;
596 			}
597 		} else if (tp->flag & LOW_BI) {
598 			/* if we have any flags, do not use the builtin */
599 			if ((ap[1] && ap[1][0] == '-' && ap[1][1] != '\0' &&
600 			    /* argument, begins with -, is not - or -- */
601 			    (ap[1][1] != '-' || ap[1][2] != '\0')) ||
602 			    /* always prefer the external utility */
603 			    (tp->flag & LOWER_BI)) {
604 				struct tbl *ext_cmd;
605 
606 				ext_cmd = findcom(tp->name, FC_FUNC | FC_PATH);
607 				if (ext_cmd && (ext_cmd->type == CFUNC ||
608 				    (ext_cmd->flag & ISSET)))
609 					tp = ext_cmd;
610 			}
611 			break;
612 		} else if (tp->val.f == c_trap) {
613 			t->u.evalflags &= ~DOTCOMEXEC;
614 			break;
615 		} else
616 			break;
617 		tp = findcom(ap[0], fcflags & (FC_BI | FC_FUNC));
618 	}
619 	if (t->u.evalflags & DOTCOMEXEC)
620 		flags |= XEXEC;
621 	l_expand = e->loc;
622 	if (!resetspec && (!ap[0] || (tp && (tp->flag & KEEPASN))))
623 		type_flags = 0;
624 	else {
625 		/* create new variable/function block */
626 		newblock();
627 		/* all functions keep assignments */
628 		type_flags = LOCAL | LOCAL_COPY | EXPORT;
629 	}
630 	l_assign = e->loc;
631 	if (exec_clrenv)
632 		l_assign->flags |= BF_STOPENV;
633 	if (Flag(FEXPORT))
634 		type_flags |= EXPORT;
635 	if (Flag(FXTRACE))
636 		change_xtrace(2, false);
637 	for (i = 0; t->vars[i]; i++) {
638 		/* do NOT lookup in the new var/fn block just created */
639 		e->loc = l_expand;
640 		cp = evalstr(t->vars[i], DOASNTILDE | DOSCALAR);
641 		e->loc = l_assign;
642 		if (Flag(FXTRACE)) {
643 			const char *ccp;
644 
645 			ccp = skip_varname(cp, true);
646 			if (*ccp == '+')
647 				++ccp;
648 			if (*ccp == '=')
649 				++ccp;
650 			shf_write(cp, ccp - cp, shl_xtrace);
651 			print_value_quoted(shl_xtrace, ccp);
652 			shf_putc(' ', shl_xtrace);
653 		}
654 		/* but assign in there as usual */
655 		typeset(cp, type_flags, 0, 0, 0);
656 	}
657 
658 	if (Flag(FXTRACE)) {
659 		change_xtrace(2, false);
660 		if (ap[rv = 0]) {
661  xtrace_ap_loop:
662 			print_value_quoted(shl_xtrace, ap[rv]);
663 			if (ap[++rv]) {
664 				shf_putc(' ', shl_xtrace);
665 				goto xtrace_ap_loop;
666 			}
667 		}
668 		change_xtrace(1, false);
669 	}
670 
671 	if ((cp = *ap) == NULL) {
672 		rv = subst_exstat;
673 		goto Leave;
674 	} else if (!tp) {
675 		if (Flag(FRESTRICTED) && mksh_vdirsep(cp)) {
676 			warningf(true, Tf_sD_s, cp, "restricted");
677 			rv = 1;
678 			goto Leave;
679 		}
680 		tp = findcom(cp, fcflags);
681 	}
682 
683 	switch (tp->type) {
684 
685 	/* shell built-in */
686 	case CSHELL:
687  do_call_builtin:
688 		if (l_expand != l_assign)
689 			l_assign->flags |= (tp->flag & NEXTLOC_BI);
690 		rv = call_builtin(tp, (const char **)ap, null, resetspec);
691 		break;
692 
693 	/* function call */
694 	case CFUNC: {
695 		volatile uint32_t old_inuse;
696 		const char * volatile old_kshname;
697 		volatile uint8_t old_flags[FNFLAGS];
698 
699 		if (!(tp->flag & ISSET)) {
700 			struct tbl *ftp;
701 
702 			if (!tp->u.fpath) {
703  fpath_error:
704 				rv = (tp->u2.errnov == ENOENT) ? 127 : 126;
705 				warningf(true, Tf_sD_s_sD_s, cp,
706 				    Tcant_find, Tfile_fd,
707 				    cstrerror(tp->u2.errnov));
708 				break;
709 			}
710 			errno = 0;
711 			if (include(tp->u.fpath, 0, NULL, false) < 0 ||
712 			    !(ftp = findfunc(cp, hash(cp), false)) ||
713 			    !(ftp->flag & ISSET)) {
714 				rv = errno;
715 				if ((ftp = findcom(cp, FC_BI)) &&
716 				    (ftp->type == CSHELL) &&
717 				    (ftp->flag & LOW_BI)) {
718 					tp = ftp;
719 					goto do_call_builtin;
720 				}
721 				if (rv) {
722 					tp->u2.errnov = rv;
723 					cp = tp->u.fpath;
724 					goto fpath_error;
725 				}
726 				warningf(true, Tf_sD_s_s, cp,
727 				    "function not defined by", tp->u.fpath);
728 				rv = 127;
729 				break;
730 			}
731 			tp = ftp;
732 		}
733 
734 		/*
735 		 * ksh functions set $0 to function name, POSIX
736 		 * functions leave $0 unchanged.
737 		 */
738 		old_kshname = kshname;
739 		if (tp->flag & FKSH)
740 			kshname = ap[0];
741 		else
742 			ap[0] = kshname;
743 		e->loc->argv = ap;
744 		for (i = 0; *ap++ != NULL; i++)
745 			;
746 		e->loc->argc = i - 1;
747 		/*
748 		 * ksh-style functions handle getopts sanely,
749 		 * Bourne/POSIX functions are insane...
750 		 */
751 		if (tp->flag & FKSH) {
752 			e->loc->flags |= BF_DOGETOPTS;
753 			e->loc->getopts_state = user_opt;
754 			getopts_reset(1);
755 		}
756 
757 		for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
758 			old_flags[type_flags] = shell_flags[type_flags];
759 		change_xtrace((Flag(FXTRACEREC) ? Flag(FXTRACE) : 0) |
760 		    ((tp->flag & TRACE) ? 1 : 0), false);
761 		old_inuse = tp->flag & FINUSE;
762 		tp->flag |= FINUSE;
763 
764 		e->type = E_FUNC;
765 		if (!(i = kshsetjmp(e->jbuf))) {
766 			execute(tp->val.t, flags & XERROK, NULL);
767 			i = LRETURN;
768 		}
769 
770 		kshname = old_kshname;
771 		change_xtrace(old_flags[(int)FXTRACE], false);
772 #ifndef MKSH_LEGACY_MODE
773 		if (tp->flag & FKSH) {
774 			/* Korn style functions restore Flags on return */
775 			old_flags[(int)FXTRACE] = Flag(FXTRACE);
776 			for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
777 				shell_flags[type_flags] = old_flags[type_flags];
778 		}
779 #endif
780 		tp->flag = (tp->flag & ~FINUSE) | old_inuse;
781 
782 		/*
783 		 * Were we deleted while executing? If so, free the
784 		 * execution tree.
785 		 */
786 		if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
787 			if (tp->flag & ALLOC) {
788 				tp->flag &= ~ALLOC;
789 				tfree(tp->val.t, tp->areap);
790 			}
791 			tp->flag = 0;
792 		}
793 		switch (i) {
794 		case LRETURN:
795 		case LERROR:
796 		case LERREXT:
797 			rv = exstat & 0xFF;
798 			break;
799 		case LINTR:
800 		case LEXIT:
801 		case LLEAVE:
802 		case LSHELL:
803 			quitenv(NULL);
804 			unwind(i);
805 			/* NOTREACHED */
806 		default:
807 			quitenv(NULL);
808 			internal_errorf(Tunexpected_type, Tunwind, Tfunction, i);
809 		}
810 		break;
811 	}
812 
813 	/* executable command */
814 	case CEXEC:
815 	/* tracked alias */
816 	case CTALIAS:
817 		if (!(tp->flag&ISSET)) {
818 			if (tp->u2.errnov == ENOENT) {
819 				rv = 127;
820 				warningf(true, Tf_sD_s_s, cp,
821 				    "inaccessible or", Tnot_found);
822 			} else {
823 				rv = 126;
824 				warningf(true, Tf_sD_sD_s, cp, "can't execute",
825 				    cstrerror(tp->u2.errnov));
826 			}
827 			break;
828 		}
829 
830 		/* set $_ to program's full path */
831 		/* setstr() can't fail here */
832 		setstr(typeset("_", LOCAL | EXPORT, 0, INTEGER, 0),
833 		    tp->val.s, KSH_RETURN_ERROR);
834 
835 		/* to fork, we set up a TEXEC node and call execute */
836 		texec.type = TEXEC;
837 		/* for vistree/dumptree */
838 		texec.left = t;
839 		texec.str = tp->val.s;
840 		texec.args = ap;
841 
842 		/* in this case we do not fork, of course */
843 		if (flags & XEXEC) {
844 			if (exec_argv0)
845 				texec.args[0] = exec_argv0;
846 			j_exit();
847 			if (!(flags & XBGND)
848 #ifndef MKSH_UNEMPLOYED
849 			    || Flag(FMONITOR)
850 #endif
851 			    ) {
852 				setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
853 				setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
854 			}
855 		}
856 
857 		rv = exchild(&texec, flags, xerrok, -1);
858 		break;
859 	}
860  Leave:
861 	if (flags & XEXEC) {
862 		exstat = rv & 0xFF;
863 		unwind(LEXIT);
864 	}
865 	return (rv);
866 }
867 
868 static void
scriptexec(struct op * tp,const char ** ap)869 scriptexec(struct op *tp, const char **ap)
870 {
871 	const char *sh;
872 #ifndef MKSH_SMALL
873 	int fd;
874 	unsigned char buf[68];
875 #endif
876 	union mksh_ccphack args, cap;
877 
878 	sh = str_val(global(TEXECSHELL));
879 	if (sh && *sh)
880 		sh = search_path(sh, path, X_OK, NULL);
881 	if (!sh || !*sh)
882 		sh = MKSH_DEFAULT_EXECSHELL;
883 
884 	*tp->args-- = tp->str;
885 
886 #ifndef MKSH_SMALL
887 	if ((fd = binopen2(tp->str, O_RDONLY | O_MAYEXEC)) >= 0) {
888 		unsigned char *cp;
889 #ifndef MKSH_EBCDIC
890 		unsigned short m;
891 #endif
892 		ssize_t n;
893 
894 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
895 		setmode(fd, O_TEXT);
896 #endif
897 		/* read first couple of octets from file */
898 		n = read(fd, buf, sizeof(buf) - 1);
899 		close(fd);
900 		/* read error or short read? */
901 		if (n < 5)
902 			goto nomagic;
903 		/* terminate buffer */
904 		buf[n] = '\0';
905 
906 		/* skip UTF-8 Byte Order Mark, if present */
907 		cp = buf + (n = ((buf[0] == 0xEF) && (buf[1] == 0xBB) &&
908 		    (buf[2] == 0xBF)) ? 3 : 0);
909 
910 		/* scan for newline or NUL (end of buffer) */
911 		while (!ctype(*cp, C_NL | C_NUL))
912 			++cp;
913 		/* if the shebang line is longer than MAXINTERP, bail out */
914 		if (!*cp)
915 			goto noshebang;
916 		/* replace newline by NUL */
917 		*cp = '\0';
918 
919 		/* restore start of shebang position (buf+0 or buf+3) */
920 		cp = buf + n;
921 		/* bail out if no shebang magic found */
922 		if (cp[0] == '#' && cp[1] == '!')
923 			cp += 2;
924 #ifdef __OS2__
925 		else if (!strncmp(cp, Textproc, 7) &&
926 		    ctype(cp[7], C_BLANK))
927 			cp += 8;
928 #endif
929 		else
930 			goto noshebang;
931 		/* skip whitespace before shell name */
932 		while (ctype(*cp, C_BLANK))
933 			++cp;
934 		/* just whitespace on the line? */
935 		if (*cp == '\0')
936 			goto noshebang;
937 		/* no, we actually found an interpreter name */
938 		sh = (char *)cp;
939 		/* look for end of shell/interpreter name */
940 		while (!ctype(*cp, C_BLANK | C_NUL))
941 			++cp;
942 		/* any arguments? */
943 		if (*cp) {
944 			*cp++ = '\0';
945 			/* skip spaces before arguments */
946 			while (ctype(*cp, C_BLANK))
947 				++cp;
948 			/* pass it all in ONE argument (historic reasons) */
949 			if (*cp)
950 				*tp->args-- = (char *)cp;
951 		}
952 #ifdef __OS2__
953 		/*
954 		 * On OS/2, the directory structure differs from normal
955 		 * Unix, which can make many scripts whose shebang
956 		 * hardcodes the path to an interpreter fail (and there
957 		 * might be no /usr/bin/env); for user convenience, if
958 		 * the specified interpreter is not usable, do a PATH
959 		 * search to find it.
960 		 */
961 		if (mksh_vdirsep(sh) && !search_path(sh, path, X_OK, NULL)) {
962 			cp = search_path(_getname(sh), path, X_OK, NULL);
963 			if (cp)
964 				sh = cp;
965 		}
966 #endif
967 		goto nomagic;
968  noshebang:
969 #ifndef MKSH_EBCDIC
970 		m = buf[0] << 8 | buf[1];
971 		if (m == 0x7F45 && buf[2] == 'L' && buf[3] == 'F')
972 			errorf("%s: not executable: %d-bit ELF file", tp->str,
973 			    32 * buf[4]);
974 		if ((m == /* OMAGIC */ 0407) ||
975 		    (m == /* NMAGIC */ 0410) ||
976 		    (m == /* ZMAGIC */ 0413) ||
977 		    (m == /* QMAGIC */ 0314) ||
978 		    (m == /* ECOFF_I386 */ 0x4C01) ||
979 		    (m == /* ECOFF_M68K */ 0x0150 || m == 0x5001) ||
980 		    (m == /* ECOFF_SH */   0x0500 || m == 0x0005) ||
981 		    (m == /* bzip */ 0x425A) || (m == /* "MZ" */ 0x4D5A) ||
982 		    (m == /* "NE" */ 0x4E45) || (m == /* "LX" */ 0x4C58) ||
983 		    (m == /* ksh93 */ 0x0B13) || (m == /* LZIP */ 0x4C5A) ||
984 		    (m == /* xz */ 0xFD37 && buf[2] == 'z' && buf[3] == 'X' &&
985 		    buf[4] == 'Z') || (m == /* 7zip */ 0x377A) ||
986 		    (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D))
987 			errorf("%s: not executable: magic %04X", tp->str, m);
988 #endif
989 #ifdef __OS2__
990 		cp = _getext(tp->str);
991 		if (cp && (!stricmp(cp, ".cmd") || !stricmp(cp, ".bat"))) {
992 			/* execute .cmd and .bat with OS2_SHELL, usually CMD.EXE */
993 			sh = str_val(global("OS2_SHELL"));
994 			*tp->args-- = "/c";
995 			/* convert slahes to backslashes */
996 			for (cp = tp->str; *cp; cp++) {
997 				if (*cp == '/')
998 					*cp = '\\';
999 			}
1000 		}
1001 #endif
1002  nomagic:
1003 		;
1004 	}
1005 #endif
1006 	args.ro = tp->args;
1007 	*args.ro = sh;
1008 
1009 	cap.ro = ap;
1010 	execve(args.rw[0], args.rw, cap.rw);
1011 
1012 	/* report both the program that was run and the bogus interpreter */
1013 	errorf(Tf_sD_sD_s, tp->str, sh, cstrerror(errno));
1014 }
1015 
1016 /* actual 'builtin' built-in utility call is handled in comexec() */
1017 int
c_builtin(const char ** wp)1018 c_builtin(const char **wp)
1019 {
1020 	return (call_builtin(get_builtin(*wp), wp, Tbuiltin, false));
1021 }
1022 
1023 struct tbl *
get_builtin(const char * s)1024 get_builtin(const char *s)
1025 {
1026 	return (s && *s ? ktsearch(&builtins, s, hash(s)) : NULL);
1027 }
1028 
1029 /*
1030  * Search function tables for a function. If create set, a table entry
1031  * is created if none is found.
1032  */
1033 struct tbl *
findfunc(const char * name,uint32_t h,bool create)1034 findfunc(const char *name, uint32_t h, bool create)
1035 {
1036 	struct block *l;
1037 	struct tbl *tp = NULL;
1038 
1039 	for (l = e->loc; l; l = l->next) {
1040 		tp = ktsearch(&l->funs, name, h);
1041 		if (tp)
1042 			break;
1043 		if (!l->next && create) {
1044 			tp = ktenter(&l->funs, name, h);
1045 			tp->flag = DEFINED;
1046 			tp->type = CFUNC;
1047 			tp->val.t = NULL;
1048 			break;
1049 		}
1050 	}
1051 	return (tp);
1052 }
1053 
1054 /*
1055  * define function. Returns 1 if function is being undefined (t == 0) and
1056  * function did not exist, returns 0 otherwise.
1057  */
1058 int
define(const char * name,struct op * t)1059 define(const char *name, struct op *t)
1060 {
1061 	uint32_t nhash;
1062 	struct tbl *tp;
1063 	bool was_set = false;
1064 
1065 	nhash = hash(name);
1066 
1067 	while (/* CONSTCOND */ 1) {
1068 		tp = findfunc(name, nhash, true);
1069 
1070 		if (tp->flag & ISSET)
1071 			was_set = true;
1072 		/*
1073 		 * If this function is currently being executed, we zap
1074 		 * this table entry so findfunc() won't see it
1075 		 */
1076 		if (tp->flag & FINUSE) {
1077 			tp->name[0] = '\0';
1078 			/* ensure it won't be found */
1079 			tp->flag &= ~DEFINED;
1080 			tp->flag |= FDELETE;
1081 		} else
1082 			break;
1083 	}
1084 
1085 	if (tp->flag & ALLOC) {
1086 		tp->flag &= ~(ISSET|ALLOC|FKSH);
1087 		tfree(tp->val.t, tp->areap);
1088 	}
1089 
1090 	if (t == NULL) {
1091 		/* undefine */
1092 		ktdelete(tp);
1093 		return (was_set ? 0 : 1);
1094 	}
1095 
1096 	tp->val.t = tcopy(t->left, tp->areap);
1097 	tp->flag |= (ISSET|ALLOC);
1098 	if (t->u.ksh_func)
1099 		tp->flag |= FKSH;
1100 
1101 	return (0);
1102 }
1103 
1104 /*
1105  * add builtin
1106  */
1107 const char *
builtin(const char * name,int (* func)(const char **))1108 builtin(const char *name, int (*func) (const char **))
1109 {
1110 	struct tbl *tp;
1111 	uint32_t flag = DEFINED;
1112 
1113 	/* see if any flags should be set for this builtin */
1114  flags_loop:
1115 	switch (*name) {
1116 	case '=':
1117 		/* command does variable assignment */
1118 		flag |= KEEPASN;
1119 		break;
1120 	case '*':
1121 		/* POSIX special builtin */
1122 		flag |= SPEC_BI;
1123 		break;
1124 	case '~':
1125 		/* external utility overrides built-in utility, always */
1126 		flag |= LOWER_BI;
1127 		/* FALLTHROUGH */
1128 	case '!':
1129 		/* external utility overrides built-in utility, with flags */
1130 		flag |= LOW_BI;
1131 		break;
1132 	case '-':
1133 		/* is declaration utility if argv[1] is one (POSIX: command) */
1134 		flag |= DECL_FWDR;
1135 		break;
1136 	case '^':
1137 		/* is declaration utility (POSIX: export, readonly) */
1138 		flag |= DECL_UTIL;
1139 		break;
1140 	case '#':
1141 		/* is set or shift */
1142 		flag |= NEXTLOC_BI;
1143 		break;
1144 	default:
1145 		goto flags_seen;
1146 	}
1147 	++name;
1148 	goto flags_loop;
1149  flags_seen:
1150 
1151 	/* enter into the builtins hash table */
1152 	tp = ktenter(&builtins, name, hash(name));
1153 	tp->flag = flag;
1154 	tp->type = CSHELL;
1155 	tp->val.f = func;
1156 
1157 	/* return name, for direct builtin call check in main.c */
1158 	return (name);
1159 }
1160 
1161 /*
1162  * find command
1163  * either function, hashed command, or built-in (in that order)
1164  */
1165 struct tbl *
findcom(const char * name,int flags)1166 findcom(const char *name, int flags)
1167 {
1168 	static struct tbl temp;
1169 	uint32_t h = hash(name);
1170 	struct tbl *tp = NULL, *tbi;
1171 	/* insert if not found */
1172 	unsigned char insert = Flag(FTRACKALL);
1173 	/* for function autoloading */
1174 	char *fpath;
1175 	union mksh_cchack npath;
1176 
1177 	if (mksh_vdirsep(name)) {
1178 		insert = 0;
1179 		/* prevent FPATH search below */
1180 		flags &= ~FC_FUNC;
1181 		goto Search;
1182 	}
1183 	tbi = (flags & FC_BI) ? ktsearch(&builtins, name, h) : NULL;
1184 	/*
1185 	 * POSIX says special builtins first, then functions, then
1186 	 * regular builtins, then search path...
1187 	 */
1188 	if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
1189 		tp = tbi;
1190 	if (!tp && (flags & FC_FUNC)) {
1191 		tp = findfunc(name, h, false);
1192 		if (tp && !(tp->flag & ISSET)) {
1193 			if ((fpath = str_val(global(TFPATH))) == null) {
1194 				tp->u.fpath = NULL;
1195 				tp->u2.errnov = ENOENT;
1196 			} else
1197 				tp->u.fpath = search_path(name, fpath, R_OK,
1198 				    &tp->u2.errnov);
1199 		}
1200 	}
1201 	if (!tp && (flags & FC_NORMBI) && tbi)
1202 		tp = tbi;
1203 	if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
1204 		tp = ktsearch(&taliases, name, h);
1205 		if (tp && (tp->flag & ISSET) &&
1206 		    ksh_access(tp->val.s, X_OK) != 0) {
1207 			if (tp->flag & ALLOC) {
1208 				tp->flag &= ~ALLOC;
1209 				afree(tp->val.s, APERM);
1210 			}
1211 			tp->flag &= ~ISSET;
1212 		}
1213 	}
1214 
1215  Search:
1216 	if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
1217 	    (flags & FC_PATH)) {
1218 		if (!tp) {
1219 			if (insert && !(flags & FC_DEFPATH)) {
1220 				tp = ktenter(&taliases, name, h);
1221 				tp->type = CTALIAS;
1222 			} else {
1223 				tp = &temp;
1224 				tp->type = CEXEC;
1225 			}
1226 			/* make ~ISSET */
1227 			tp->flag = DEFINED;
1228 		}
1229 		npath.ro = search_path(name,
1230 		    (flags & FC_DEFPATH) ? def_path : path,
1231 		    X_OK, &tp->u2.errnov);
1232 		if (npath.ro) {
1233 			strdupx(tp->val.s, npath.ro, APERM);
1234 			if (npath.ro != name)
1235 				afree(npath.rw, ATEMP);
1236 			tp->flag |= ISSET|ALLOC;
1237 		} else if ((flags & FC_FUNC) &&
1238 		    (fpath = str_val(global(TFPATH))) != null &&
1239 		    (npath.ro = search_path(name, fpath, R_OK,
1240 		    &tp->u2.errnov)) != NULL) {
1241 			/*
1242 			 * An undocumented feature of AT&T ksh is that
1243 			 * it searches FPATH if a command is not found,
1244 			 * even if the command hasn't been set up as an
1245 			 * autoloaded function (ie, no typeset -uf).
1246 			 */
1247 			tp = &temp;
1248 			tp->type = CFUNC;
1249 			/* make ~ISSET */
1250 			tp->flag = DEFINED;
1251 			tp->u.fpath = npath.ro;
1252 		}
1253 	}
1254 	return (tp);
1255 }
1256 
1257 /*
1258  * flush executable commands with relative paths
1259  * (just relative or all?)
1260  */
1261 void
flushcom(bool all)1262 flushcom(bool all)
1263 {
1264 	struct tbl *tp;
1265 	struct tstate ts;
1266 
1267 	for (ktwalk(&ts, &taliases); (tp = ktnext(&ts)) != NULL; )
1268 		if ((tp->flag&ISSET) && (all || !mksh_abspath(tp->val.s))) {
1269 			if (tp->flag&ALLOC) {
1270 				tp->flag &= ~(ALLOC|ISSET);
1271 				afree(tp->val.s, APERM);
1272 			}
1273 			tp->flag &= ~ISSET;
1274 		}
1275 }
1276 
1277 /* check if path is something we want to find */
1278 int
search_access(const char * fn,int mode)1279 search_access(const char *fn, int mode)
1280 {
1281 	struct stat sb;
1282 
1283 	if (stat(fn, &sb) < 0)
1284 		/* file does not exist */
1285 		return (ENOENT);
1286 	/* LINTED use of access */
1287 	if (access(fn, mode) < 0) {
1288 		/* file exists, but we can't access it */
1289 		int eno;
1290 
1291 		eno = errno;
1292 		return (eno ? eno : EACCES);
1293 	}
1294 #ifdef __OS2__
1295 	/* treat all files as executable on OS/2 */
1296 	sb.st_mode |= S_IXUSR | S_IXGRP | S_IXOTH;
1297 #endif
1298 	if (mode == X_OK && (!S_ISREG(sb.st_mode) ||
1299 	    !(sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
1300 		/* access(2) may say root can execute everything */
1301 		return (S_ISDIR(sb.st_mode) ? EISDIR : EACCES);
1302 	return (0);
1303 }
1304 
1305 #ifdef __OS2__
1306 /* check if path is something we want to find adding executable extensions */
1307 #define search_access(fn,mode)	access_ex((search_access), (fn), (mode))
1308 #else
1309 #define search_access(fn,mode)	(search_access)((fn), (mode))
1310 #endif
1311 
1312 /*
1313  * search for command with PATH
1314  */
1315 const char *
search_path(const char * name,const char * lpath,int mode,int * errnop)1316 search_path(const char *name, const char *lpath,
1317     /* R_OK or X_OK */
1318     int mode,
1319     /* set if candidate found, but not suitable */
1320     int *errnop)
1321 {
1322 	const char *sp, *p;
1323 	char *xp;
1324 	XString xs;
1325 	size_t namelen;
1326 	int ec = 0, ev;
1327 
1328 	if (mksh_vdirsep(name)) {
1329 		if ((ec = search_access(name, mode)) == 0) {
1330  search_path_ok:
1331 			if (errnop)
1332 				*errnop = 0;
1333 #ifndef __OS2__
1334 			return (name);
1335 #else
1336 			return (real_exec_name(name));
1337 #endif
1338 		}
1339 		goto search_path_err;
1340 	}
1341 
1342 	namelen = strlen(name) + 1;
1343 	Xinit(xs, xp, 128, ATEMP);
1344 
1345 	sp = lpath;
1346 	while (sp != NULL) {
1347 		xp = Xstring(xs, xp);
1348 		if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
1349 			p = strnul(sp);
1350 		if (p != sp) {
1351 			XcheckN(xs, xp, p - sp);
1352 			memcpy(xp, sp, p - sp);
1353 			xp += p - sp;
1354 #ifdef __OS2__
1355 			if (xp > Xstring(xs, xp) && mksh_cdirsep(xp[-1]))
1356 				xp--;
1357 #endif
1358 			*xp++ = '/';
1359 		}
1360 		sp = p;
1361 		XcheckN(xs, xp, namelen);
1362 		memcpy(xp, name, namelen);
1363 		if ((ev = search_access(Xstring(xs, xp), mode)) == 0) {
1364 			name = Xclose(xs, xp + namelen);
1365 			goto search_path_ok;
1366 		}
1367 		/* accumulate non-ENOENT errors only */
1368 		if (ev != ENOENT && ec == 0)
1369 			ec = ev;
1370 		if (*sp++ == '\0')
1371 			sp = NULL;
1372 	}
1373 	Xfree(xs, xp);
1374  search_path_err:
1375 	if (errnop)
1376 		*errnop = ec ? ec : ENOENT;
1377 	return (NULL);
1378 }
1379 
1380 static int
call_builtin(struct tbl * tp,const char ** wp,const char * where,bool resetspec)1381 call_builtin(struct tbl *tp, const char **wp, const char *where, bool resetspec)
1382 {
1383 	int rv;
1384 
1385 	if (!tp)
1386 		internal_errorf(Tf_sD_s, where, wp[0]);
1387 	builtin_argv0 = wp[0];
1388 	builtin_spec = tobool(!resetspec && (tp->flag & SPEC_BI));
1389 	shf_reopen(1, SHF_WR, shl_stdout);
1390 	shl_stdout_ok = true;
1391 	ksh_getopt_reset(&builtin_opt, GF_ERROR);
1392 	rv = (*tp->val.f)(wp);
1393 	shf_flush(shl_stdout);
1394 	shl_stdout_ok = false;
1395 	builtin_argv0 = NULL;
1396 	builtin_spec = false;
1397 	return (rv);
1398 }
1399 
1400 /*
1401  * set up redirection, saving old fds in e->savefd
1402  */
1403 static int
iosetup(struct ioword * iop,struct tbl * tp)1404 iosetup(struct ioword *iop, struct tbl *tp)
1405 {
1406 	int u = -1;
1407 	char *cp = iop->ioname;
1408 	int iotype = iop->ioflag & IOTYPE;
1409 	bool do_open = true, do_close = false, do_fstat = false;
1410 	int flags = 0;
1411 	struct ioword iotmp;
1412 	struct stat statb;
1413 
1414 	if (iotype != IOHERE)
1415 		cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1416 
1417 	/* Used for tracing and error messages to print expanded cp */
1418 	iotmp = *iop;
1419 	iotmp.ioname = (iotype == IOHERE) ? NULL : cp;
1420 	iotmp.ioflag |= IONAMEXP;
1421 
1422 	if (Flag(FXTRACE)) {
1423 		change_xtrace(2, false);
1424 		fptreef(shl_xtrace, 0, Tft_R, &iotmp);
1425 		change_xtrace(1, false);
1426 	}
1427 
1428 	switch (iotype) {
1429 	case IOREAD:
1430 		flags = O_RDONLY;
1431 		break;
1432 
1433 	case IOCAT:
1434 		flags = O_WRONLY | O_APPEND | O_CREAT;
1435 		break;
1436 
1437 	case IOWRITE:
1438 		if (Flag(FNOCLOBBER) && !(iop->ioflag & IOCLOB)) {
1439 			/* >file under set -C */
1440 			if (stat(cp, &statb)) {
1441 				/* nonexistent file */
1442 				flags = O_WRONLY | O_CREAT | O_EXCL;
1443 			} else if (S_ISREG(statb.st_mode)) {
1444 				/* regular file, refuse clobbering */
1445 				goto clobber_refused;
1446 			} else {
1447 				/*
1448 				 * allow redirections to things
1449 				 * like /dev/null without error
1450 				 */
1451 				flags = O_WRONLY;
1452 				/* but check again after opening */
1453 				do_fstat = true;
1454 			}
1455 		} else {
1456 			/* >|file or set +C */
1457 			flags = O_WRONLY | O_CREAT | O_TRUNC;
1458 		}
1459 		break;
1460 
1461 	case IORDWR:
1462 		flags = O_RDWR | O_CREAT;
1463 		break;
1464 
1465 	case IOHERE:
1466 		do_open = false;
1467 		/* herein() returns -2 if error has been printed */
1468 		u = herein(iop, NULL);
1469 		/* cp may have wrong name */
1470 		break;
1471 
1472 	case IODUP: {
1473 		const char *emsg;
1474 
1475 		do_open = false;
1476 		if (ksh_isdash(cp)) {
1477 			/* prevent error return below */
1478 			u = 1009;
1479 			do_close = true;
1480 		} else if ((u = check_fd(cp,
1481 		    X_OK | ((iop->ioflag & IORDUP) ? R_OK : W_OK),
1482 		    &emsg)) < 0) {
1483 			char *sp;
1484 
1485 			warningf(true, Tf_sD_s,
1486 			    (sp = snptreef(NULL, 32, Tft_R, &iotmp)), emsg);
1487 			afree(sp, ATEMP);
1488 			return (-1);
1489 		}
1490 		if (u == (int)iop->unit) {
1491 			/* "dup from" == "dup to" */
1492 			iop->ioflag |= IODUPSELF;
1493 			return (0);
1494 		}
1495 		break;
1496 	    }
1497 	}
1498 
1499 	if (do_open) {
1500 		if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
1501 			warningf(true, Tf_sD_s, cp, "restricted");
1502 			return (-1);
1503 		}
1504 		u = binopen3(cp, flags, 0666);
1505 		if (do_fstat && u >= 0) {
1506 			/* prevent race conditions */
1507 			if (fstat(u, &statb) || S_ISREG(statb.st_mode)) {
1508 				close(u);
1509  clobber_refused:
1510 				u = -1;
1511 				errno = EEXIST;
1512 			}
1513 		}
1514 	}
1515 	if (u < 0) {
1516 		/* herein() may already have printed message */
1517 		if (u == -1) {
1518 			u = errno;
1519 			warningf(true, Tf_cant_ss_s,
1520 #if 0
1521 			    /* can't happen */
1522 			    iotype == IODUP ? "dup" :
1523 #endif
1524 			    (iotype == IOREAD || iotype == IOHERE) ?
1525 			    Topen : Tcreate, cp, cstrerror(u));
1526 		}
1527 		return (-1);
1528 	}
1529 	/* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1530 	if (e->savefd[iop->unit] == 0) {
1531 		/* If these are the same, it means unit was previously closed */
1532 		if (u == (int)iop->unit)
1533 			e->savefd[iop->unit] = -1;
1534 		else
1535 			/*
1536 			 * c_exec() assumes e->savefd[fd] set for any
1537 			 * redirections. Ask savefd() not to close iop->unit;
1538 			 * this allows error messages to be seen if iop->unit
1539 			 * is 2; also means we can't lose the fd (eg, both
1540 			 * dup2 below and dup2 in restfd() failing).
1541 			 */
1542 			e->savefd[iop->unit] = savefd(iop->unit);
1543 	}
1544 
1545 	if (do_close)
1546 		close(iop->unit);
1547 	else if (u != (int)iop->unit) {
1548 		if (ksh_dup2(u, iop->unit, true) < 0) {
1549 			int eno;
1550 			char *sp;
1551 
1552 			eno = errno;
1553 			warningf(true, Tf_s_sD_s, Tredirection_dup,
1554 			    (sp = snptreef(NULL, 32, Tft_R, &iotmp)),
1555 			    cstrerror(eno));
1556 			afree(sp, ATEMP);
1557 			if (iotype != IODUP)
1558 				close(u);
1559 			return (-1);
1560 		}
1561 		if (iotype != IODUP)
1562 			close(u);
1563 		/*
1564 		 * Touching any co-process fd in an empty exec
1565 		 * causes the shell to close its copies
1566 		 */
1567 		else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1568 			if (iop->ioflag & IORDUP)
1569 				/* possible exec <&p */
1570 				coproc_read_close(u);
1571 			else
1572 				/* possible exec >&p */
1573 				coproc_write_close(u);
1574 		}
1575 	}
1576 	if (u == 2)
1577 		/* Clear any write errors */
1578 		shf_reopen(2, SHF_WR, shl_out);
1579 	return (0);
1580 }
1581 
1582 /*
1583  * Process here documents by providing the content, either as
1584  * result (globally allocated) string or in a temp file; if
1585  * unquoted, the string is expanded first.
1586  */
1587 static int
hereinval(struct ioword * iop,int sub,char ** resbuf,struct shf * shf)1588 hereinval(struct ioword *iop, int sub, char **resbuf, struct shf *shf)
1589 {
1590 	const char * volatile ccp = iop->heredoc;
1591 	struct source *s, *osource;
1592 
1593 	osource = source;
1594 	newenv(E_ERRH);
1595 	if (kshsetjmp(e->jbuf)) {
1596 		source = osource;
1597 		quitenv(shf);
1598 		/* special to iosetup(): don't print error */
1599 		return (-2);
1600 	}
1601 	if (iop->ioflag & IOHERESTR) {
1602 		ccp = evalstr(iop->delim, DOHERESTR | DOSCALAR);
1603 	} else if (sub) {
1604 		/* do substitutions on the content of heredoc */
1605 		s = pushs(SSTRING, ATEMP);
1606 		s->start = s->str = ccp;
1607 		source = s;
1608 		if (yylex(sub) != LWORD)
1609 			internal_errorf("herein: yylex");
1610 		source = osource;
1611 		ccp = evalstr(yylval.cp, DOSCALAR | DOHEREDOC);
1612 	}
1613 
1614 	if (resbuf == NULL)
1615 		shf_puts(ccp, shf);
1616 	else
1617 		strdupx(*resbuf, ccp, APERM);
1618 
1619 	quitenv(NULL);
1620 	return (0);
1621 }
1622 
1623 int
herein(struct ioword * iop,char ** resbuf)1624 herein(struct ioword *iop, char **resbuf)
1625 {
1626 	int fd = -1;
1627 	struct shf *shf;
1628 	struct temp *h;
1629 	int i;
1630 
1631 	/* lexer substitution flags */
1632 	i = (iop->ioflag & IOEVAL) ? (ONEWORD | HEREDOC) : 0;
1633 
1634 	/* skip all the fd setup if we just want the value */
1635 	if (resbuf != NULL)
1636 		return (hereinval(iop, i, resbuf, NULL));
1637 
1638 	/*
1639 	 * Create temp file to hold content (done before newenv
1640 	 * so temp doesn't get removed too soon).
1641 	 */
1642 	h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1643 	if (!(shf = h->shf) || (fd = binopen3(h->tffn, O_RDONLY, 0)) < 0) {
1644 		i = errno;
1645 		warningf(true, Tf_temp,
1646 		    !shf ? Tcreate : Topen, h->tffn, cstrerror(i));
1647 		if (shf)
1648 			shf_close(shf);
1649 		/* special to iosetup(): don't print error */
1650 		return (-2);
1651 	}
1652 
1653 	if (hereinval(iop, i, NULL, shf) == -2) {
1654 		close(fd);
1655 		/* special to iosetup(): don't print error */
1656 		return (-2);
1657 	}
1658 
1659 	if (shf_close(shf) == -1) {
1660 		i = errno;
1661 		close(fd);
1662 		warningf(true, Tf_temp,
1663 		    Twrite, h->tffn, cstrerror(i));
1664 		/* special to iosetup(): don't print error */
1665 		return (-2);
1666 	}
1667 
1668 	return (fd);
1669 }
1670 
1671 /*
1672  *	ksh special - the select command processing section
1673  *	print the args in column form - assuming that we can
1674  */
1675 static const char *
do_selectargs(const char ** ap,bool print_menu)1676 do_selectargs(const char **ap, bool print_menu)
1677 {
1678 	static const char *read_args[] = {
1679 		Tread, Tdr, TREPLY, NULL
1680 	};
1681 	char *s;
1682 	int i, argct;
1683 
1684 	for (argct = 0; ap[argct]; argct++)
1685 		;
1686 	while (/* CONSTCOND */ 1) {
1687 		/*-
1688 		 * Menu is printed if
1689 		 *	- this is the first time around the select loop
1690 		 *	- the user enters a blank line
1691 		 *	- the REPLY parameter is empty
1692 		 */
1693 		if (print_menu || !*str_val(global(TREPLY)))
1694 			pr_menu(ap);
1695 		shellf(Tf_s, str_val(global("PS3")));
1696 		if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect,
1697 		    false))
1698 			return (NULL);
1699 		if (*(s = str_val(global(TREPLY))))
1700 			return ((getn(s, &i) && i >= 1 && i <= argct) ?
1701 			    ap[i - 1] : null);
1702 		print_menu = true;
1703 	}
1704 }
1705 
1706 struct select_menu_info {
1707 	const char * const *args;
1708 	int num_width;
1709 };
1710 
1711 /* format a single select menu item */
1712 static void
select_fmt_entry(char * buf,size_t buflen,unsigned int i,const void * arg)1713 select_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1714 {
1715 	const struct select_menu_info *smi =
1716 	    (const struct select_menu_info *)arg;
1717 
1718 	shf_snprintf(buf, buflen, "%*u) %s",
1719 	    smi->num_width, i + 1, smi->args[i]);
1720 }
1721 
1722 /*
1723  *	print a select style menu
1724  */
1725 void
pr_menu(const char * const * ap)1726 pr_menu(const char * const *ap)
1727 {
1728 	struct select_menu_info smi;
1729 	const char * const *pp;
1730 	size_t acols = 0, aocts = 0, i;
1731 	unsigned int n;
1732 	struct columnise_opts co;
1733 
1734 	/*
1735 	 * width/column calculations were done once and saved, but this
1736 	 * means select can't be used recursively so we re-calculate
1737 	 * each time (could save in a structure that is returned, but
1738 	 * it's probably not worth the bother)
1739 	 */
1740 
1741 	/*
1742 	 * get dimensions of the list
1743 	 */
1744 	for (n = 0, pp = ap; *pp; n++, pp++) {
1745 		i = strlen(*pp);
1746 		if (i > aocts)
1747 			aocts = i;
1748 		i = utf_mbswidth(*pp);
1749 		if (i > acols)
1750 			acols = i;
1751 	}
1752 
1753 	/*
1754 	 * we will print an index of the form "%d) " in front of
1755 	 * each entry, so get the maximum width of this
1756 	 */
1757 	for (i = n, smi.num_width = 1; i >= 10; i /= 10)
1758 		smi.num_width++;
1759 
1760 	smi.args = ap;
1761 	co.shf = shl_out;
1762 	co.linesep = '\n';
1763 	co.prefcol = co.do_last = true;
1764 	print_columns(&co, n, select_fmt_entry, (void *)&smi,
1765 	    smi.num_width + 2 + aocts, smi.num_width + 2 + acols);
1766 }
1767 
1768 static void
plain_fmt_entry(char * buf,size_t buflen,unsigned int i,const void * arg)1769 plain_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1770 {
1771 	strlcpy(buf, ((const char * const *)arg)[i], buflen);
1772 }
1773 
1774 void
pr_list(struct columnise_opts * cop,char * const * ap)1775 pr_list(struct columnise_opts *cop, char * const *ap)
1776 {
1777 	size_t acols = 0, aocts = 0, i;
1778 	unsigned int n;
1779 	char * const *pp;
1780 
1781 	for (n = 0, pp = ap; *pp; n++, pp++) {
1782 		i = strlen(*pp);
1783 		if (i > aocts)
1784 			aocts = i;
1785 		i = utf_mbswidth(*pp);
1786 		if (i > acols)
1787 			acols = i;
1788 	}
1789 
1790 	print_columns(cop, n, plain_fmt_entry, (const void *)ap,
1791 	    aocts, acols);
1792 }
1793 
1794 /*
1795  *	[[ ... ]] evaluation routines
1796  */
1797 
1798 /*
1799  * Test if the current token is a whatever. Accepts the current token if
1800  * it is. Returns 0 if it is not, non-zero if it is (in the case of
1801  * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1802  */
1803 static Test_op
dbteste_isa(Test_env * te,Test_meta meta)1804 dbteste_isa(Test_env *te, Test_meta meta)
1805 {
1806 	Test_op ret = TO_NONOP;
1807 	bool uqword;
1808 	const char *p;
1809 
1810 	if (!*te->pos.wp)
1811 		return (meta == TM_END ? TO_NONNULL : TO_NONOP);
1812 
1813 	/* unquoted word? */
1814 	for (p = *te->pos.wp; *p == CHAR; p += 2)
1815 		;
1816 	uqword = *p == EOS;
1817 
1818 	if (meta == TM_UNOP || meta == TM_BINOP) {
1819 		if (uqword) {
1820 			/* longer than the longest operator */
1821 			char buf[8];
1822 			char *q = buf;
1823 
1824 			p = *te->pos.wp;
1825 			while (*p++ == CHAR &&
1826 			    (size_t)(q - buf) < sizeof(buf) - 1)
1827 				*q++ = *p++;
1828 			*q = '\0';
1829 			ret = test_isop(meta, buf);
1830 		}
1831 	} else if (meta == TM_END)
1832 		ret = TO_NONOP;
1833 	else
1834 		ret = (uqword && !strcmp(*te->pos.wp,
1835 		    dbtest_tokens[(int)meta])) ? TO_NONNULL : TO_NONOP;
1836 
1837 	/* Accept the token? */
1838 	if (ret != TO_NONOP)
1839 		te->pos.wp++;
1840 
1841 	return (ret);
1842 }
1843 
1844 static const char *
dbteste_getopnd(Test_env * te,Test_op op,bool do_eval)1845 dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
1846 {
1847 	const char *s = *te->pos.wp;
1848 	int flags = DOTILDE | DOSCALAR;
1849 
1850 	if (!s)
1851 		return (NULL);
1852 
1853 	te->pos.wp++;
1854 
1855 	if (!do_eval)
1856 		return (null);
1857 
1858 	if (op == TO_STEQL || op == TO_STNEQ) {
1859 		flags |= DOPAT;
1860 		if (!Flag(FSH))
1861 			flags |= DODBMAGIC;
1862 	}
1863 
1864 	return (evalstr(s, flags));
1865 }
1866 
1867 static void
dbteste_error(Test_env * te,int offset,const char * msg)1868 dbteste_error(Test_env *te, int offset, const char *msg)
1869 {
1870 	te->flags |= TEF_ERROR;
1871 	internal_warningf("dbteste_error: %s (offset %d)", msg, offset);
1872 }
1873