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
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.206 2019/03/01 16:17:53 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 dp = shf_smprintf(Tf_ss, evalstr(t->vars[0],
112 DOASNTILDE | DOSCALAR), 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 errorf(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 if (Flag(FERREXIT) & 0x80) {
468 /* inside eval */
469 Flag(FERREXIT) = 0;
470 } else {
471 trapsig(ksh_SIGERR);
472 if (Flag(FERREXIT))
473 unwind(LERROR);
474 }
475 }
476 return (rv);
477 }
478
479 /*
480 * execute simple command
481 */
482
483 static int
comexec(struct op * t,struct tbl * volatile tp,const char ** ap,volatile int flags,volatile int * xerrok)484 comexec(struct op *t, struct tbl * volatile tp, const char **ap,
485 volatile int flags, volatile int *xerrok)
486 {
487 int i;
488 volatile int rv = 0;
489 const char *cp;
490 const char **lastp;
491 /* Must be static (XXX but why?) */
492 static struct op texec;
493 int type_flags;
494 bool resetspec;
495 int fcflags = FC_BI|FC_FUNC|FC_PATH;
496 struct block *l_expand, *l_assign;
497 int optc;
498 const char *exec_argv0 = NULL;
499 bool exec_clrenv = false;
500
501 /* snag the last argument for $_ */
502 if (Flag(FTALKING) && *(lastp = ap)) {
503 /*
504 * XXX not the same as AT&T ksh, which only seems to set $_
505 * after a newline (but not in functions/dot scripts, but in
506 * interactive and script) - perhaps save last arg here and
507 * set it in shell()?.
508 */
509 while (*++lastp)
510 ;
511 /* setstr() can't fail here */
512 setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
513 KSH_RETURN_ERROR);
514 }
515
516 /**
517 * Deal with the shell builtins builtin, exec and command since
518 * they can be followed by other commands. This must be done before
519 * we know if we should create a local block which must be done
520 * before we can do a path search (in case the assignments change
521 * PATH).
522 * Odd cases:
523 * FOO=bar exec >/dev/null FOO is kept but not exported
524 * FOO=bar exec foobar FOO is exported
525 * FOO=bar command exec >/dev/null FOO is neither kept nor exported
526 * FOO=bar command FOO is neither kept nor exported
527 * PATH=... foobar use new PATH in foobar search
528 */
529 resetspec = false;
530 while (tp && tp->type == CSHELL) {
531 /* undo effects of command */
532 fcflags = FC_BI|FC_FUNC|FC_PATH;
533 if (tp->val.f == c_builtin) {
534 if ((cp = *++ap) == NULL ||
535 (!strcmp(cp, "--") && (cp = *++ap) == NULL)) {
536 tp = NULL;
537 break;
538 }
539 if ((tp = findcom(cp, FC_BI)) == NULL)
540 errorf(Tf_sD_sD_s, Tbuiltin, cp, Tnot_found);
541 if (tp->type == CSHELL && (tp->flag & LOW_BI))
542 break;
543 continue;
544 } else if (tp->val.f == c_exec) {
545 if (ap[1] == NULL)
546 break;
547 ksh_getopt_reset(&builtin_opt, GF_ERROR);
548 while ((optc = ksh_getopt(ap, &builtin_opt, "a:c")) != -1)
549 switch (optc) {
550 case 'a':
551 exec_argv0 = builtin_opt.optarg;
552 break;
553 case 'c':
554 exec_clrenv = true;
555 /* ensure we can actually do this */
556 resetspec = true;
557 break;
558 default:
559 rv = 2;
560 goto Leave;
561 }
562 ap += builtin_opt.optind;
563 flags |= XEXEC;
564 /* POSuX demands ksh88-like behaviour here */
565 if (Flag(FPOSIX))
566 fcflags = FC_PATH;
567 #ifndef MKSH_LESS_BUILDINS
568 } else if (tp->val.f == c_command) {
569 bool saw_p = false;
570
571 /*
572 * Ugly dealing with options in two places (here
573 * and in c_command(), but such is life)
574 */
575 ksh_getopt_reset(&builtin_opt, 0);
576 while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
577 saw_p = true;
578 if (optc != -1)
579 /* command -vV or something */
580 break;
581 /* don't look for functions */
582 fcflags = FC_BI|FC_PATH;
583 if (saw_p) {
584 if (Flag(FRESTRICTED)) {
585 warningf(true, Tf_sD_s,
586 "command -p", "restricted");
587 rv = 1;
588 goto Leave;
589 }
590 fcflags |= FC_DEFPATH;
591 }
592 ap += builtin_opt.optind;
593 /*
594 * POSIX says special builtins lose their status
595 * if accessed using command.
596 */
597 resetspec = true;
598 if (!ap[0]) {
599 /* ensure command with no args exits with 0 */
600 subst_exstat = 0;
601 break;
602 }
603 #endif // MKSH_LESS_BUILDINS
604 } else if (tp->flag & LOW_BI) {
605 /* if we have any flags, do not use the builtin */
606 if ((ap[1] && ap[1][0] == '-' && ap[1][1] != '\0' &&
607 /* argument, begins with -, is not - or -- */
608 (ap[1][1] != '-' || ap[1][2] != '\0')) ||
609 /* always prefer the external utility */
610 (tp->flag & LOWER_BI)) {
611 struct tbl *ext_cmd;
612
613 ext_cmd = findcom(tp->name, FC_PATH | FC_FUNC);
614 if (ext_cmd && (ext_cmd->type != CTALIAS ||
615 (ext_cmd->flag & ISSET)))
616 tp = ext_cmd;
617 }
618 break;
619 } else if (tp->val.f == c_trap) {
620 t->u.evalflags &= ~DOTCOMEXEC;
621 break;
622 } else
623 break;
624 tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
625 }
626 if (t->u.evalflags & DOTCOMEXEC)
627 flags |= XEXEC;
628 l_expand = e->loc;
629 if (!resetspec && (!ap[0] || (tp && (tp->flag & KEEPASN))))
630 type_flags = 0;
631 else {
632 /* create new variable/function block */
633 newblock();
634 /* ksh functions don't keep assignments, POSIX functions do. */
635 if (!resetspec && tp && tp->type == CFUNC &&
636 !(tp->flag & FKSH))
637 type_flags = EXPORT;
638 else
639 type_flags = LOCAL|LOCAL_COPY|EXPORT;
640 }
641 l_assign = e->loc;
642 if (exec_clrenv)
643 l_assign->flags |= BF_STOPENV;
644 if (Flag(FEXPORT))
645 type_flags |= EXPORT;
646 if (Flag(FXTRACE))
647 change_xtrace(2, false);
648 for (i = 0; t->vars[i]; i++) {
649 /* do NOT lookup in the new var/fn block just created */
650 e->loc = l_expand;
651 cp = evalstr(t->vars[i], DOASNTILDE | DOSCALAR);
652 e->loc = l_assign;
653 if (Flag(FXTRACE)) {
654 const char *ccp;
655
656 ccp = skip_varname(cp, true);
657 if (*ccp == '+')
658 ++ccp;
659 if (*ccp == '=')
660 ++ccp;
661 shf_write(cp, ccp - cp, shl_xtrace);
662 print_value_quoted(shl_xtrace, ccp);
663 shf_putc(' ', shl_xtrace);
664 }
665 /* but assign in there as usual */
666 typeset(cp, type_flags, 0, 0, 0);
667 }
668
669 if (Flag(FXTRACE)) {
670 change_xtrace(2, false);
671 if (ap[rv = 0]) {
672 xtrace_ap_loop:
673 print_value_quoted(shl_xtrace, ap[rv]);
674 if (ap[++rv]) {
675 shf_putc(' ', shl_xtrace);
676 goto xtrace_ap_loop;
677 }
678 }
679 change_xtrace(1, false);
680 }
681
682 if ((cp = *ap) == NULL) {
683 rv = subst_exstat;
684 goto Leave;
685 } else if (!tp) {
686 if (Flag(FRESTRICTED) && mksh_vdirsep(cp)) {
687 warningf(true, Tf_sD_s, cp, "restricted");
688 rv = 1;
689 goto Leave;
690 }
691 tp = findcom(cp, fcflags);
692 }
693
694 switch (tp->type) {
695
696 /* shell built-in */
697 case CSHELL:
698 do_call_builtin:
699 rv = call_builtin(tp, (const char **)ap, null, resetspec);
700 if (resetspec && tp->val.f == c_shift) {
701 l_expand->argc = l_assign->argc;
702 l_expand->argv = l_assign->argv;
703 }
704 break;
705
706 /* function call */
707 case CFUNC: {
708 volatile uint32_t old_inuse;
709 const char * volatile old_kshname;
710 volatile uint8_t old_flags[FNFLAGS];
711
712 if (!(tp->flag & ISSET)) {
713 struct tbl *ftp;
714
715 if (!tp->u.fpath) {
716 fpath_error:
717 rv = (tp->u2.errnov == ENOENT) ? 127 : 126;
718 warningf(true, Tf_sD_s_sD_s, cp,
719 Tcant_find, Tfile_fd,
720 cstrerror(tp->u2.errnov));
721 break;
722 }
723 errno = 0;
724 if (include(tp->u.fpath, 0, NULL, false) < 0 ||
725 !(ftp = findfunc(cp, hash(cp), false)) ||
726 !(ftp->flag & ISSET)) {
727 rv = errno;
728 if ((ftp = findcom(cp, FC_BI)) &&
729 (ftp->type == CSHELL) &&
730 (ftp->flag & LOW_BI)) {
731 tp = ftp;
732 goto do_call_builtin;
733 }
734 if (rv) {
735 tp->u2.errnov = rv;
736 cp = tp->u.fpath;
737 goto fpath_error;
738 }
739 warningf(true, Tf_sD_s_s, cp,
740 "function not defined by", tp->u.fpath);
741 rv = 127;
742 break;
743 }
744 tp = ftp;
745 }
746
747 /*
748 * ksh functions set $0 to function name, POSIX
749 * functions leave $0 unchanged.
750 */
751 old_kshname = kshname;
752 if (tp->flag & FKSH)
753 kshname = ap[0];
754 else
755 ap[0] = kshname;
756 e->loc->argv = ap;
757 for (i = 0; *ap++ != NULL; i++)
758 ;
759 e->loc->argc = i - 1;
760 /*
761 * ksh-style functions handle getopts sanely,
762 * Bourne/POSIX functions are insane...
763 */
764 if (tp->flag & FKSH) {
765 e->loc->flags |= BF_DOGETOPTS;
766 e->loc->getopts_state = user_opt;
767 getopts_reset(1);
768 }
769
770 for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
771 old_flags[type_flags] = shell_flags[type_flags];
772 change_xtrace((Flag(FXTRACEREC) ? Flag(FXTRACE) : 0) |
773 ((tp->flag & TRACE) ? 1 : 0), false);
774 old_inuse = tp->flag & FINUSE;
775 tp->flag |= FINUSE;
776
777 e->type = E_FUNC;
778 if (!(i = kshsetjmp(e->jbuf))) {
779 execute(tp->val.t, flags & XERROK, NULL);
780 i = LRETURN;
781 }
782
783 kshname = old_kshname;
784 change_xtrace(old_flags[(int)FXTRACE], false);
785 #ifndef MKSH_LEGACY_MODE
786 if (tp->flag & FKSH) {
787 /* Korn style functions restore Flags on return */
788 old_flags[(int)FXTRACE] = Flag(FXTRACE);
789 for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
790 shell_flags[type_flags] = old_flags[type_flags];
791 }
792 #endif
793 tp->flag = (tp->flag & ~FINUSE) | old_inuse;
794
795 /*
796 * Were we deleted while executing? If so, free the
797 * execution tree.
798 */
799 if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
800 if (tp->flag & ALLOC) {
801 tp->flag &= ~ALLOC;
802 tfree(tp->val.t, tp->areap);
803 }
804 tp->flag = 0;
805 }
806 switch (i) {
807 case LRETURN:
808 case LERROR:
809 rv = exstat & 0xFF;
810 break;
811 case LINTR:
812 case LEXIT:
813 case LLEAVE:
814 case LSHELL:
815 quitenv(NULL);
816 unwind(i);
817 /* NOTREACHED */
818 default:
819 quitenv(NULL);
820 internal_errorf(Tunexpected_type, Tunwind, Tfunction, i);
821 }
822 break;
823 }
824
825 /* executable command */
826 case CEXEC:
827 /* tracked alias */
828 case CTALIAS:
829 if (!(tp->flag&ISSET)) {
830 if (tp->u2.errnov == ENOENT) {
831 rv = 127;
832 warningf(true, Tf_sD_s_s, cp,
833 "inaccessible or", Tnot_found);
834 } else {
835 rv = 126;
836 warningf(true, Tf_sD_sD_s, cp, "can't execute",
837 cstrerror(tp->u2.errnov));
838 }
839 break;
840 }
841
842 /* set $_ to program's full path */
843 /* setstr() can't fail here */
844 setstr(typeset("_", LOCAL | EXPORT, 0, INTEGER, 0),
845 tp->val.s, KSH_RETURN_ERROR);
846
847 /* to fork, we set up a TEXEC node and call execute */
848 texec.type = TEXEC;
849 /* for vistree/dumptree */
850 texec.left = t;
851 texec.str = tp->val.s;
852 texec.args = ap;
853
854 /* in this case we do not fork, of course */
855 if (flags & XEXEC) {
856 if (exec_argv0)
857 texec.args[0] = exec_argv0;
858 j_exit();
859 if (!(flags & XBGND)
860 #ifndef MKSH_UNEMPLOYED
861 || Flag(FMONITOR)
862 #endif
863 ) {
864 setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
865 setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
866 }
867 }
868
869 rv = exchild(&texec, flags, xerrok, -1);
870 break;
871 }
872 Leave:
873 if (flags & XEXEC) {
874 exstat = rv & 0xFF;
875 unwind(LEXIT);
876 }
877 return (rv);
878 }
879
880 static void
scriptexec(struct op * tp,const char ** ap)881 scriptexec(struct op *tp, const char **ap)
882 {
883 const char *sh;
884 #ifndef MKSH_SMALL
885 int fd;
886 unsigned char buf[68];
887 #endif
888 union mksh_ccphack args, cap;
889
890 sh = str_val(global(TEXECSHELL));
891 if (sh && *sh)
892 sh = search_path(sh, path, X_OK, NULL);
893 if (!sh || !*sh)
894 sh = MKSH_DEFAULT_EXECSHELL;
895
896 *tp->args-- = tp->str;
897
898 #ifndef MKSH_SMALL
899 if ((fd = binopen2(tp->str, O_RDONLY | O_MAYEXEC)) >= 0) {
900 unsigned char *cp;
901 #ifndef MKSH_EBCDIC
902 unsigned short m;
903 #endif
904 ssize_t n;
905
906 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
907 setmode(fd, O_TEXT);
908 #endif
909 /* read first couple of octets from file */
910 n = read(fd, buf, sizeof(buf) - 1);
911 close(fd);
912 /* read error or short read? */
913 if (n < 5)
914 goto nomagic;
915 /* terminate buffer */
916 buf[n] = '\0';
917
918 /* skip UTF-8 Byte Order Mark, if present */
919 cp = buf + (n = ((buf[0] == 0xEF) && (buf[1] == 0xBB) &&
920 (buf[2] == 0xBF)) ? 3 : 0);
921
922 /* scan for newline or NUL (end of buffer) */
923 while (!ctype(*cp, C_NL | C_NUL))
924 ++cp;
925 /* if the shebang line is longer than MAXINTERP, bail out */
926 if (!*cp)
927 goto noshebang;
928 /* replace newline by NUL */
929 *cp = '\0';
930
931 /* restore start of shebang position (buf+0 or buf+3) */
932 cp = buf + n;
933 /* bail out if no shebang magic found */
934 if (cp[0] == '#' && cp[1] == '!')
935 cp += 2;
936 #ifdef __OS2__
937 else if (!strncmp(cp, Textproc, 7) &&
938 ctype(cp[7], C_BLANK))
939 cp += 8;
940 #endif
941 else
942 goto noshebang;
943 /* skip whitespace before shell name */
944 while (ctype(*cp, C_BLANK))
945 ++cp;
946 /* just whitespace on the line? */
947 if (*cp == '\0')
948 goto noshebang;
949 /* no, we actually found an interpreter name */
950 sh = (char *)cp;
951 /* look for end of shell/interpreter name */
952 while (!ctype(*cp, C_BLANK | C_NUL))
953 ++cp;
954 /* any arguments? */
955 if (*cp) {
956 *cp++ = '\0';
957 /* skip spaces before arguments */
958 while (ctype(*cp, C_BLANK))
959 ++cp;
960 /* pass it all in ONE argument (historic reasons) */
961 if (*cp)
962 *tp->args-- = (char *)cp;
963 }
964 #ifdef __OS2__
965 /*
966 * On OS/2, the directory structure differs from normal
967 * Unix, which can make many scripts whose shebang
968 * hardcodes the path to an interpreter fail (and there
969 * might be no /usr/bin/env); for user convenience, if
970 * the specified interpreter is not usable, do a PATH
971 * search to find it.
972 */
973 if (mksh_vdirsep(sh) && !search_path(sh, path, X_OK, NULL)) {
974 cp = search_path(_getname(sh), path, X_OK, NULL);
975 if (cp)
976 sh = cp;
977 }
978 #endif
979 goto nomagic;
980 noshebang:
981 #ifndef MKSH_EBCDIC
982 m = buf[0] << 8 | buf[1];
983 if (m == 0x7F45 && buf[2] == 'L' && buf[3] == 'F')
984 errorf("%s: not executable: %d-bit ELF file", tp->str,
985 32 * buf[4]);
986 if ((m == /* OMAGIC */ 0407) ||
987 (m == /* NMAGIC */ 0410) ||
988 (m == /* ZMAGIC */ 0413) ||
989 (m == /* QMAGIC */ 0314) ||
990 (m == /* ECOFF_I386 */ 0x4C01) ||
991 (m == /* ECOFF_M68K */ 0x0150 || m == 0x5001) ||
992 (m == /* ECOFF_SH */ 0x0500 || m == 0x0005) ||
993 (m == /* bzip */ 0x425A) || (m == /* "MZ" */ 0x4D5A) ||
994 (m == /* "NE" */ 0x4E45) || (m == /* "LX" */ 0x4C58) ||
995 (m == /* ksh93 */ 0x0B13) || (m == /* LZIP */ 0x4C5A) ||
996 (m == /* xz */ 0xFD37 && buf[2] == 'z' && buf[3] == 'X' &&
997 buf[4] == 'Z') || (m == /* 7zip */ 0x377A) ||
998 (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D))
999 errorf("%s: not executable: magic %04X", tp->str, m);
1000 #endif
1001 #ifdef __OS2__
1002 cp = _getext(tp->str);
1003 if (cp && (!stricmp(cp, ".cmd") || !stricmp(cp, ".bat"))) {
1004 /* execute .cmd and .bat with OS2_SHELL, usually CMD.EXE */
1005 sh = str_val(global("OS2_SHELL"));
1006 *tp->args-- = "/c";
1007 /* convert slahes to backslashes */
1008 for (cp = tp->str; *cp; cp++) {
1009 if (*cp == '/')
1010 *cp = '\\';
1011 }
1012 }
1013 #endif
1014 nomagic:
1015 ;
1016 }
1017 #endif
1018 args.ro = tp->args;
1019 *args.ro = sh;
1020
1021 cap.ro = ap;
1022 execve(args.rw[0], args.rw, cap.rw);
1023
1024 /* report both the program that was run and the bogus interpreter */
1025 errorf(Tf_sD_sD_s, tp->str, sh, cstrerror(errno));
1026 }
1027
1028 /* actual 'builtin' built-in utility call is handled in comexec() */
1029 int
c_builtin(const char ** wp)1030 c_builtin(const char **wp)
1031 {
1032 return (call_builtin(get_builtin(*wp), wp, Tbuiltin, false));
1033 }
1034
1035 struct tbl *
get_builtin(const char * s)1036 get_builtin(const char *s)
1037 {
1038 return (s && *s ? ktsearch(&builtins, s, hash(s)) : NULL);
1039 }
1040
1041 /*
1042 * Search function tables for a function. If create set, a table entry
1043 * is created if none is found.
1044 */
1045 struct tbl *
findfunc(const char * name,uint32_t h,bool create)1046 findfunc(const char *name, uint32_t h, bool create)
1047 {
1048 struct block *l;
1049 struct tbl *tp = NULL;
1050
1051 for (l = e->loc; l; l = l->next) {
1052 tp = ktsearch(&l->funs, name, h);
1053 if (tp)
1054 break;
1055 if (!l->next && create) {
1056 tp = ktenter(&l->funs, name, h);
1057 tp->flag = DEFINED;
1058 tp->type = CFUNC;
1059 tp->val.t = NULL;
1060 break;
1061 }
1062 }
1063 return (tp);
1064 }
1065
1066 /*
1067 * define function. Returns 1 if function is being undefined (t == 0) and
1068 * function did not exist, returns 0 otherwise.
1069 */
1070 int
define(const char * name,struct op * t)1071 define(const char *name, struct op *t)
1072 {
1073 uint32_t nhash;
1074 struct tbl *tp;
1075 bool was_set = false;
1076
1077 nhash = hash(name);
1078
1079 while (/* CONSTCOND */ 1) {
1080 tp = findfunc(name, nhash, true);
1081
1082 if (tp->flag & ISSET)
1083 was_set = true;
1084 /*
1085 * If this function is currently being executed, we zap
1086 * this table entry so findfunc() won't see it
1087 */
1088 if (tp->flag & FINUSE) {
1089 tp->name[0] = '\0';
1090 /* ensure it won't be found */
1091 tp->flag &= ~DEFINED;
1092 tp->flag |= FDELETE;
1093 } else
1094 break;
1095 }
1096
1097 if (tp->flag & ALLOC) {
1098 tp->flag &= ~(ISSET|ALLOC|FKSH);
1099 tfree(tp->val.t, tp->areap);
1100 }
1101
1102 if (t == NULL) {
1103 /* undefine */
1104 ktdelete(tp);
1105 return (was_set ? 0 : 1);
1106 }
1107
1108 tp->val.t = tcopy(t->left, tp->areap);
1109 tp->flag |= (ISSET|ALLOC);
1110 if (t->u.ksh_func)
1111 tp->flag |= FKSH;
1112
1113 return (0);
1114 }
1115
1116 /*
1117 * add builtin
1118 */
1119 const char *
builtin(const char * name,int (* func)(const char **))1120 builtin(const char *name, int (*func) (const char **))
1121 {
1122 struct tbl *tp;
1123 uint32_t flag = DEFINED;
1124
1125 /* see if any flags should be set for this builtin */
1126 flags_loop:
1127 switch (*name) {
1128 case '=':
1129 /* command does variable assignment */
1130 flag |= KEEPASN;
1131 break;
1132 case '*':
1133 /* POSIX special builtin */
1134 flag |= SPEC_BI;
1135 break;
1136 case '~':
1137 /* external utility overrides built-in utility, always */
1138 flag |= LOWER_BI;
1139 /* FALLTHROUGH */
1140 case '!':
1141 /* external utility overrides built-in utility, with flags */
1142 flag |= LOW_BI;
1143 break;
1144 case '-':
1145 /* is declaration utility if argv[1] is one (POSIX: command) */
1146 flag |= DECL_FWDR;
1147 break;
1148 case '^':
1149 /* is declaration utility (POSIX: export, readonly) */
1150 flag |= DECL_UTIL;
1151 break;
1152 default:
1153 goto flags_seen;
1154 }
1155 ++name;
1156 goto flags_loop;
1157 flags_seen:
1158
1159 /* enter into the builtins hash table */
1160 tp = ktenter(&builtins, name, hash(name));
1161 tp->flag = flag;
1162 tp->type = CSHELL;
1163 tp->val.f = func;
1164
1165 /* return name, for direct builtin call check in main.c */
1166 return (name);
1167 }
1168
1169 /*
1170 * find command
1171 * either function, hashed command, or built-in (in that order)
1172 */
1173 struct tbl *
findcom(const char * name,int flags)1174 findcom(const char *name, int flags)
1175 {
1176 static struct tbl temp;
1177 uint32_t h = hash(name);
1178 struct tbl *tp = NULL, *tbi;
1179 /* insert if not found */
1180 unsigned char insert = Flag(FTRACKALL);
1181 /* for function autoloading */
1182 char *fpath;
1183 union mksh_cchack npath;
1184
1185 if (mksh_vdirsep(name)) {
1186 insert = 0;
1187 /* prevent FPATH search below */
1188 flags &= ~FC_FUNC;
1189 goto Search;
1190 }
1191 tbi = (flags & FC_BI) ? ktsearch(&builtins, name, h) : NULL;
1192 /*
1193 * POSIX says special builtins first, then functions, then
1194 * regular builtins, then search path...
1195 */
1196 if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
1197 tp = tbi;
1198 if (!tp && (flags & FC_FUNC)) {
1199 tp = findfunc(name, h, false);
1200 if (tp && !(tp->flag & ISSET)) {
1201 if ((fpath = str_val(global(TFPATH))) == null) {
1202 tp->u.fpath = NULL;
1203 tp->u2.errnov = ENOENT;
1204 } else
1205 tp->u.fpath = search_path(name, fpath, R_OK,
1206 &tp->u2.errnov);
1207 }
1208 }
1209 if (!tp && (flags & FC_NORMBI) && tbi)
1210 tp = tbi;
1211 if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
1212 tp = ktsearch(&taliases, name, h);
1213 if (tp && (tp->flag & ISSET) &&
1214 ksh_access(tp->val.s, X_OK) != 0) {
1215 if (tp->flag & ALLOC) {
1216 tp->flag &= ~ALLOC;
1217 afree(tp->val.s, APERM);
1218 }
1219 tp->flag &= ~ISSET;
1220 }
1221 }
1222
1223 Search:
1224 if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
1225 (flags & FC_PATH)) {
1226 if (!tp) {
1227 if (insert && !(flags & FC_DEFPATH)) {
1228 tp = ktenter(&taliases, name, h);
1229 tp->type = CTALIAS;
1230 } else {
1231 tp = &temp;
1232 tp->type = CEXEC;
1233 }
1234 /* make ~ISSET */
1235 tp->flag = DEFINED;
1236 }
1237 npath.ro = search_path(name,
1238 (flags & FC_DEFPATH) ? def_path : path,
1239 X_OK, &tp->u2.errnov);
1240 if (npath.ro) {
1241 strdupx(tp->val.s, npath.ro, APERM);
1242 if (npath.ro != name)
1243 afree(npath.rw, ATEMP);
1244 tp->flag |= ISSET|ALLOC;
1245 } else if ((flags & FC_FUNC) &&
1246 (fpath = str_val(global(TFPATH))) != null &&
1247 (npath.ro = search_path(name, fpath, R_OK,
1248 &tp->u2.errnov)) != NULL) {
1249 /*
1250 * An undocumented feature of AT&T ksh is that
1251 * it searches FPATH if a command is not found,
1252 * even if the command hasn't been set up as an
1253 * autoloaded function (ie, no typeset -uf).
1254 */
1255 tp = &temp;
1256 tp->type = CFUNC;
1257 /* make ~ISSET */
1258 tp->flag = DEFINED;
1259 tp->u.fpath = npath.ro;
1260 }
1261 }
1262 return (tp);
1263 }
1264
1265 /*
1266 * flush executable commands with relative paths
1267 * (just relative or all?)
1268 */
1269 void
flushcom(bool all)1270 flushcom(bool all)
1271 {
1272 struct tbl *tp;
1273 struct tstate ts;
1274
1275 for (ktwalk(&ts, &taliases); (tp = ktnext(&ts)) != NULL; )
1276 if ((tp->flag&ISSET) && (all || !mksh_abspath(tp->val.s))) {
1277 if (tp->flag&ALLOC) {
1278 tp->flag &= ~(ALLOC|ISSET);
1279 afree(tp->val.s, APERM);
1280 }
1281 tp->flag &= ~ISSET;
1282 }
1283 }
1284
1285 /* check if path is something we want to find */
1286 int
search_access(const char * fn,int mode)1287 search_access(const char *fn, int mode)
1288 {
1289 struct stat sb;
1290
1291 if (stat(fn, &sb) < 0)
1292 /* file does not exist */
1293 return (ENOENT);
1294 /* LINTED use of access */
1295 if (access(fn, mode) < 0) {
1296 /* file exists, but we can't access it */
1297 int eno;
1298
1299 eno = errno;
1300 return (eno ? eno : EACCES);
1301 }
1302 #ifdef __OS2__
1303 /* treat all files as executable on OS/2 */
1304 sb.st_mode |= S_IXUSR | S_IXGRP | S_IXOTH;
1305 #endif
1306 if (mode == X_OK && (!S_ISREG(sb.st_mode) ||
1307 !(sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))))
1308 /* access(2) may say root can execute everything */
1309 return (S_ISDIR(sb.st_mode) ? EISDIR : EACCES);
1310 return (0);
1311 }
1312
1313 #ifdef __OS2__
1314 /* check if path is something we want to find, adding executable extensions */
1315 #define search_access(fn, mode) access_ex((search_access), (fn), (mode))
1316 #else
1317 #define search_access(fn, mode) (search_access)((fn), (mode))
1318 #endif
1319
1320 /*
1321 * search for command with PATH
1322 */
1323 const char *
search_path(const char * name,const char * lpath,int mode,int * errnop)1324 search_path(const char *name, const char *lpath,
1325 /* R_OK or X_OK */
1326 int mode,
1327 /* set if candidate found, but not suitable */
1328 int *errnop)
1329 {
1330 const char *sp, *p;
1331 char *xp;
1332 XString xs;
1333 size_t namelen;
1334 int ec = 0, ev;
1335
1336 if (mksh_vdirsep(name)) {
1337 if ((ec = search_access(name, mode)) == 0) {
1338 search_path_ok:
1339 if (errnop)
1340 *errnop = 0;
1341 #ifndef __OS2__
1342 return (name);
1343 #else
1344 return (real_exec_name(name));
1345 #endif
1346 }
1347 goto search_path_err;
1348 }
1349
1350 namelen = strlen(name) + 1;
1351 Xinit(xs, xp, 128, ATEMP);
1352
1353 sp = lpath;
1354 while (sp != NULL) {
1355 xp = Xstring(xs, xp);
1356 if (!(p = cstrchr(sp, MKSH_PATHSEPC)))
1357 p = strnul(sp);
1358 if (p != sp) {
1359 XcheckN(xs, xp, p - sp);
1360 memcpy(xp, sp, p - sp);
1361 xp += p - sp;
1362 #ifdef __OS2__
1363 if (xp > Xstring(xs, xp) && mksh_cdirsep(xp[-1]))
1364 xp--;
1365 #endif
1366 *xp++ = '/';
1367 }
1368 sp = p;
1369 XcheckN(xs, xp, namelen);
1370 memcpy(xp, name, namelen);
1371 if ((ev = search_access(Xstring(xs, xp), mode)) == 0) {
1372 name = Xclose(xs, xp + namelen);
1373 goto search_path_ok;
1374 }
1375 /* accumulate non-ENOENT errors only */
1376 if (ev != ENOENT && ec == 0)
1377 ec = ev;
1378 if (*sp++ == '\0')
1379 sp = NULL;
1380 }
1381 Xfree(xs, xp);
1382 search_path_err:
1383 if (errnop)
1384 *errnop = ec ? ec : ENOENT;
1385 return (NULL);
1386 }
1387
1388 static int
call_builtin(struct tbl * tp,const char ** wp,const char * where,bool resetspec)1389 call_builtin(struct tbl *tp, const char **wp, const char *where, bool resetspec)
1390 {
1391 int rv;
1392
1393 if (!tp)
1394 internal_errorf(Tf_sD_s, where, wp[0]);
1395 builtin_argv0 = wp[0];
1396 builtin_spec = tobool(!resetspec && (tp->flag & SPEC_BI));
1397 shf_reopen(1, SHF_WR, shl_stdout);
1398 shl_stdout_ok = true;
1399 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1400 rv = (*tp->val.f)(wp);
1401 shf_flush(shl_stdout);
1402 shl_stdout_ok = false;
1403 builtin_argv0 = NULL;
1404 builtin_spec = false;
1405 return (rv);
1406 }
1407
1408 /*
1409 * set up redirection, saving old fds in e->savefd
1410 */
1411 static int
iosetup(struct ioword * iop,struct tbl * tp)1412 iosetup(struct ioword *iop, struct tbl *tp)
1413 {
1414 int u = -1;
1415 char *cp = iop->ioname;
1416 int iotype = iop->ioflag & IOTYPE;
1417 bool do_open = true, do_close = false, do_fstat = false;
1418 int flags = 0;
1419 struct ioword iotmp;
1420 struct stat statb;
1421
1422 if (iotype != IOHERE)
1423 cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1424
1425 /* Used for tracing and error messages to print expanded cp */
1426 iotmp = *iop;
1427 iotmp.ioname = (iotype == IOHERE) ? NULL : cp;
1428 iotmp.ioflag |= IONAMEXP;
1429
1430 if (Flag(FXTRACE)) {
1431 change_xtrace(2, false);
1432 fptreef(shl_xtrace, 0, Tft_R, &iotmp);
1433 change_xtrace(1, false);
1434 }
1435
1436 switch (iotype) {
1437 case IOREAD:
1438 flags = O_RDONLY;
1439 break;
1440
1441 case IOCAT:
1442 flags = O_WRONLY | O_APPEND | O_CREAT;
1443 break;
1444
1445 case IOWRITE:
1446 if (Flag(FNOCLOBBER) && !(iop->ioflag & IOCLOB)) {
1447 /* >file under set -C */
1448 if (stat(cp, &statb)) {
1449 /* nonexistent file */
1450 flags = O_WRONLY | O_CREAT | O_EXCL;
1451 } else if (S_ISREG(statb.st_mode)) {
1452 /* regular file, refuse clobbering */
1453 goto clobber_refused;
1454 } else {
1455 /*
1456 * allow redirections to things
1457 * like /dev/null without error
1458 */
1459 flags = O_WRONLY;
1460 /* but check again after opening */
1461 do_fstat = true;
1462 }
1463 } else {
1464 /* >|file or set +C */
1465 flags = O_WRONLY | O_CREAT | O_TRUNC;
1466 }
1467 break;
1468
1469 case IORDWR:
1470 flags = O_RDWR | O_CREAT;
1471 break;
1472
1473 case IOHERE:
1474 do_open = false;
1475 /* herein() returns -2 if error has been printed */
1476 u = herein(iop, NULL);
1477 /* cp may have wrong name */
1478 break;
1479
1480 case IODUP: {
1481 const char *emsg;
1482
1483 do_open = false;
1484 if (ksh_isdash(cp)) {
1485 /* prevent error return below */
1486 u = 1009;
1487 do_close = true;
1488 } else if ((u = check_fd(cp,
1489 X_OK | ((iop->ioflag & IORDUP) ? R_OK : W_OK),
1490 &emsg)) < 0) {
1491 char *sp;
1492
1493 warningf(true, Tf_sD_s,
1494 (sp = snptreef(NULL, 32, Tft_R, &iotmp)), emsg);
1495 afree(sp, ATEMP);
1496 return (-1);
1497 }
1498 if (u == (int)iop->unit) {
1499 /* "dup from" == "dup to" */
1500 iop->ioflag |= IODUPSELF;
1501 return (0);
1502 }
1503 break;
1504 }
1505 }
1506
1507 if (do_open) {
1508 if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
1509 warningf(true, Tf_sD_s, cp, "restricted");
1510 return (-1);
1511 }
1512 u = binopen3(cp, flags, 0666);
1513 if (do_fstat && u >= 0) {
1514 /* prevent race conditions */
1515 if (fstat(u, &statb) || S_ISREG(statb.st_mode)) {
1516 close(u);
1517 clobber_refused:
1518 u = -1;
1519 errno = EEXIST;
1520 }
1521 }
1522 }
1523 if (u < 0) {
1524 /* herein() may already have printed message */
1525 if (u == -1) {
1526 u = errno;
1527 warningf(true, Tf_cant_ss_s,
1528 #if 0
1529 /* can't happen */
1530 iotype == IODUP ? "dup" :
1531 #endif
1532 (iotype == IOREAD || iotype == IOHERE) ?
1533 Topen : Tcreate, cp, cstrerror(u));
1534 }
1535 return (-1);
1536 }
1537 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1538 if (e->savefd[iop->unit] == 0) {
1539 /* If these are the same, it means unit was previously closed */
1540 if (u == (int)iop->unit)
1541 e->savefd[iop->unit] = -1;
1542 else
1543 /*
1544 * c_exec() assumes e->savefd[fd] set for any
1545 * redirections. Ask savefd() not to close iop->unit;
1546 * this allows error messages to be seen if iop->unit
1547 * is 2; also means we can't lose the fd (eg, both
1548 * dup2 below and dup2 in restfd() failing).
1549 */
1550 e->savefd[iop->unit] = savefd(iop->unit);
1551 }
1552
1553 if (do_close)
1554 close(iop->unit);
1555 else if (u != (int)iop->unit) {
1556 if (ksh_dup2(u, iop->unit, true) < 0) {
1557 int eno;
1558 char *sp;
1559
1560 eno = errno;
1561 warningf(true, Tf_s_sD_s, Tredirection_dup,
1562 (sp = snptreef(NULL, 32, Tft_R, &iotmp)),
1563 cstrerror(eno));
1564 afree(sp, ATEMP);
1565 if (iotype != IODUP)
1566 close(u);
1567 return (-1);
1568 }
1569 if (iotype != IODUP)
1570 close(u);
1571 /*
1572 * Touching any co-process fd in an empty exec
1573 * causes the shell to close its copies
1574 */
1575 else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1576 if (iop->ioflag & IORDUP)
1577 /* possible exec <&p */
1578 coproc_read_close(u);
1579 else
1580 /* possible exec >&p */
1581 coproc_write_close(u);
1582 }
1583 }
1584 if (u == 2)
1585 /* Clear any write errors */
1586 shf_reopen(2, SHF_WR, shl_out);
1587 return (0);
1588 }
1589
1590 /*
1591 * Process here documents by providing the content, either as
1592 * result (globally allocated) string or in a temp file; if
1593 * unquoted, the string is expanded first.
1594 */
1595 static int
hereinval(struct ioword * iop,int sub,char ** resbuf,struct shf * shf)1596 hereinval(struct ioword *iop, int sub, char **resbuf, struct shf *shf)
1597 {
1598 const char * volatile ccp = iop->heredoc;
1599 struct source *s, *osource;
1600
1601 osource = source;
1602 newenv(E_ERRH);
1603 if (kshsetjmp(e->jbuf)) {
1604 source = osource;
1605 quitenv(shf);
1606 /* special to iosetup(): don't print error */
1607 return (-2);
1608 }
1609 if (iop->ioflag & IOHERESTR) {
1610 ccp = evalstr(iop->delim, DOHERESTR | DOSCALAR | DOHEREDOC);
1611 } else if (sub) {
1612 /* do substitutions on the content of heredoc */
1613 s = pushs(SSTRING, ATEMP);
1614 s->start = s->str = ccp;
1615 source = s;
1616 if (yylex(sub) != LWORD)
1617 internal_errorf("herein: yylex");
1618 source = osource;
1619 ccp = evalstr(yylval.cp, DOSCALAR | DOHEREDOC);
1620 }
1621
1622 if (resbuf == NULL)
1623 shf_puts(ccp, shf);
1624 else
1625 strdupx(*resbuf, ccp, APERM);
1626
1627 quitenv(NULL);
1628 return (0);
1629 }
1630
1631 int
herein(struct ioword * iop,char ** resbuf)1632 herein(struct ioword *iop, char **resbuf)
1633 {
1634 int fd = -1;
1635 struct shf *shf;
1636 struct temp *h;
1637 int i;
1638
1639 /* lexer substitution flags */
1640 i = (iop->ioflag & IOEVAL) ? (ONEWORD | HEREDOC) : 0;
1641
1642 /* skip all the fd setup if we just want the value */
1643 if (resbuf != NULL)
1644 return (hereinval(iop, i, resbuf, NULL));
1645
1646 /*
1647 * Create temp file to hold content (done before newenv
1648 * so temp doesn't get removed too soon).
1649 */
1650 h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1651 if (!(shf = h->shf) || (fd = binopen3(h->tffn, O_RDONLY, 0)) < 0) {
1652 i = errno;
1653 warningf(true, Tf_temp,
1654 !shf ? Tcreate : Topen, h->tffn, cstrerror(i));
1655 if (shf)
1656 shf_close(shf);
1657 /* special to iosetup(): don't print error */
1658 return (-2);
1659 }
1660
1661 if (hereinval(iop, i, NULL, shf) == -2) {
1662 close(fd);
1663 /* special to iosetup(): don't print error */
1664 return (-2);
1665 }
1666
1667 if (shf_close(shf) == -1) {
1668 i = errno;
1669 close(fd);
1670 warningf(true, Tf_temp,
1671 Twrite, h->tffn, cstrerror(i));
1672 /* special to iosetup(): don't print error */
1673 return (-2);
1674 }
1675
1676 return (fd);
1677 }
1678
1679 /*
1680 * ksh special - the select command processing section
1681 * print the args in column form - assuming that we can
1682 */
1683 static const char *
do_selectargs(const char ** ap,bool print_menu)1684 do_selectargs(const char **ap, bool print_menu)
1685 {
1686 static const char *read_args[] = {
1687 Tread, "-r", "REPLY", NULL
1688 };
1689 char *s;
1690 int i, argct;
1691
1692 for (argct = 0; ap[argct]; argct++)
1693 ;
1694 while (/* CONSTCOND */ 1) {
1695 /*-
1696 * Menu is printed if
1697 * - this is the first time around the select loop
1698 * - the user enters a blank line
1699 * - the REPLY parameter is empty
1700 */
1701 if (print_menu || !*str_val(global("REPLY")))
1702 pr_menu(ap);
1703 shellf(Tf_s, str_val(global("PS3")));
1704 if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect,
1705 false))
1706 return (NULL);
1707 if (*(s = str_val(global("REPLY"))))
1708 return ((getn(s, &i) && i >= 1 && i <= argct) ?
1709 ap[i - 1] : null);
1710 print_menu = true;
1711 }
1712 }
1713
1714 struct select_menu_info {
1715 const char * const *args;
1716 int num_width;
1717 };
1718
1719 /* format a single select menu item */
1720 static void
select_fmt_entry(char * buf,size_t buflen,unsigned int i,const void * arg)1721 select_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1722 {
1723 const struct select_menu_info *smi =
1724 (const struct select_menu_info *)arg;
1725
1726 shf_snprintf(buf, buflen, "%*u) %s",
1727 smi->num_width, i + 1, smi->args[i]);
1728 }
1729
1730 /*
1731 * print a select style menu
1732 */
1733 void
pr_menu(const char * const * ap)1734 pr_menu(const char * const *ap)
1735 {
1736 struct select_menu_info smi;
1737 const char * const *pp;
1738 size_t acols = 0, aocts = 0, i;
1739 unsigned int n;
1740 struct columnise_opts co;
1741
1742 /*
1743 * width/column calculations were done once and saved, but this
1744 * means select can't be used recursively so we re-calculate
1745 * each time (could save in a structure that is returned, but
1746 * it's probably not worth the bother)
1747 */
1748
1749 /*
1750 * get dimensions of the list
1751 */
1752 for (n = 0, pp = ap; *pp; n++, pp++) {
1753 i = strlen(*pp);
1754 if (i > aocts)
1755 aocts = i;
1756 i = utf_mbswidth(*pp);
1757 if (i > acols)
1758 acols = i;
1759 }
1760
1761 /*
1762 * we will print an index of the form "%d) " in front of
1763 * each entry, so get the maximum width of this
1764 */
1765 for (i = n, smi.num_width = 1; i >= 10; i /= 10)
1766 smi.num_width++;
1767
1768 smi.args = ap;
1769 co.shf = shl_out;
1770 co.linesep = '\n';
1771 co.prefcol = co.do_last = true;
1772 print_columns(&co, n, select_fmt_entry, (void *)&smi,
1773 smi.num_width + 2 + aocts, smi.num_width + 2 + acols);
1774 }
1775
1776 static void
plain_fmt_entry(char * buf,size_t buflen,unsigned int i,const void * arg)1777 plain_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1778 {
1779 strlcpy(buf, ((const char * const *)arg)[i], buflen);
1780 }
1781
1782 void
pr_list(struct columnise_opts * cop,char * const * ap)1783 pr_list(struct columnise_opts *cop, char * const *ap)
1784 {
1785 size_t acols = 0, aocts = 0, i;
1786 unsigned int n;
1787 char * const *pp;
1788
1789 for (n = 0, pp = ap; *pp; n++, pp++) {
1790 i = strlen(*pp);
1791 if (i > aocts)
1792 aocts = i;
1793 i = utf_mbswidth(*pp);
1794 if (i > acols)
1795 acols = i;
1796 }
1797
1798 print_columns(cop, n, plain_fmt_entry, (const void *)ap,
1799 aocts, acols);
1800 }
1801
1802 /*
1803 * [[ ... ]] evaluation routines
1804 */
1805
1806 /*
1807 * Test if the current token is a whatever. Accepts the current token if
1808 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1809 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1810 */
1811 static Test_op
dbteste_isa(Test_env * te,Test_meta meta)1812 dbteste_isa(Test_env *te, Test_meta meta)
1813 {
1814 Test_op ret = TO_NONOP;
1815 bool uqword;
1816 const char *p;
1817
1818 if (!*te->pos.wp)
1819 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
1820
1821 /* unquoted word? */
1822 for (p = *te->pos.wp; *p == CHAR; p += 2)
1823 ;
1824 uqword = *p == EOS;
1825
1826 if (meta == TM_UNOP || meta == TM_BINOP) {
1827 if (uqword) {
1828 /* longer than the longest operator */
1829 char buf[8];
1830 char *q = buf;
1831
1832 p = *te->pos.wp;
1833 while (*p++ == CHAR &&
1834 (size_t)(q - buf) < sizeof(buf) - 1)
1835 *q++ = *p++;
1836 *q = '\0';
1837 ret = test_isop(meta, buf);
1838 }
1839 } else if (meta == TM_END)
1840 ret = TO_NONOP;
1841 else
1842 ret = (uqword && !strcmp(*te->pos.wp,
1843 dbtest_tokens[(int)meta])) ? TO_NONNULL : TO_NONOP;
1844
1845 /* Accept the token? */
1846 if (ret != TO_NONOP)
1847 te->pos.wp++;
1848
1849 return (ret);
1850 }
1851
1852 static const char *
dbteste_getopnd(Test_env * te,Test_op op,bool do_eval)1853 dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
1854 {
1855 const char *s = *te->pos.wp;
1856 int flags = DOTILDE | DOSCALAR;
1857
1858 if (!s)
1859 return (NULL);
1860
1861 te->pos.wp++;
1862
1863 if (!do_eval)
1864 return (null);
1865
1866 if (op == TO_STEQL || op == TO_STNEQ)
1867 flags |= DOPAT;
1868
1869 return (evalstr(s, flags));
1870 }
1871
1872 static void
dbteste_error(Test_env * te,int offset,const char * msg)1873 dbteste_error(Test_env *te, int offset, const char *msg)
1874 {
1875 te->flags |= TEF_ERROR;
1876 internal_warningf("dbteste_error: %s (offset %d)", msg, offset);
1877 }
1878