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