1 /* $OpenBSD: exec.c,v 1.49 2009/01/29 23:27:26 jaredy Exp $ */
2
3 /*-
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 * Thorsten Glaser <tg@mirbsd.org>
6 *
7 * Provided that these terms and disclaimer and all copyright notices
8 * are retained or reproduced in an accompanying document, permission
9 * is granted to deal in this work without restriction, including un-
10 * limited rights to use, publicly perform, distribute, sell, modify,
11 * merge, give away, or sublicence.
12 *
13 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
14 * the utmost extent permitted by applicable law, neither express nor
15 * implied; without malicious intent or gross negligence. In no event
16 * may a licensor, author or contributor be held liable for indirect,
17 * direct, other damage, loss, or other issues arising in any way out
18 * of dealing in the work, even if advised of the possibility of such
19 * damage or existence of a defect, except proven that it results out
20 * of said person's immediate fault when using the work as intended.
21 */
22
23 #include "sh.h"
24
25 __RCSID("$MirOS: src/bin/mksh/exec.c,v 1.75 2010/07/17 22:09:34 tg Exp $");
26
27 #ifndef MKSH_DEFAULT_EXECSHELL
28 #define MKSH_DEFAULT_EXECSHELL "/bin/sh"
29 #endif
30
31 static int comexec(struct op *, struct tbl *volatile, const char **,
32 int volatile, volatile int *);
33 static void scriptexec(struct op *, const char **) MKSH_A_NORETURN;
34 static int call_builtin(struct tbl *, const char **);
35 static int iosetup(struct ioword *, struct tbl *);
36 static int herein(const char *, int);
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
42 /*
43 * execute command tree
44 */
45 int
execute(struct op * volatile t,volatile int flags,volatile int * volatile xerrok)46 execute(struct op *volatile t,
47 volatile int flags, /* if XEXEC don't fork */
48 volatile int * volatile xerrok)
49 {
50 int i;
51 volatile int rv = 0, dummy = 0;
52 int pv[2];
53 const char ** volatile ap;
54 char ** volatile up;
55 const char *s, *cp;
56 struct ioword **iowp;
57 struct tbl *tp = NULL;
58
59 if (t == NULL)
60 return (0);
61
62 /* Caller doesn't care if XERROK should propagate. */
63 if (xerrok == NULL)
64 xerrok = &dummy;
65
66 if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
67 /* run in sub-process */
68 return (exchild(t, flags & ~XTIME, xerrok, -1));
69
70 newenv(E_EXEC);
71 if (trap)
72 runtraps(0);
73
74 if (t->type == TCOM) {
75 /* Clear subst_exstat before argument expansion. Used by
76 * null commands (see comexec() and c_eval()) and by c_set().
77 */
78 subst_exstat = 0;
79
80 current_lineno = t->lineno; /* for $LINENO */
81
82 /* POSIX says expand command words first, then redirections,
83 * and assignments last..
84 */
85 up = eval(t->args, t->u.evalflags | DOBLANK | DOGLOB | DOTILDE);
86 if (flags & XTIME)
87 /* Allow option parsing (bizarre, but POSIX) */
88 timex_hook(t, &up);
89 ap = (const char **)up;
90 if (Flag(FXTRACE) && ap[0]) {
91 shf_fprintf(shl_out, "%s",
92 substitute(str_val(global("PS4")), 0));
93 for (i = 0; ap[i]; i++)
94 shf_fprintf(shl_out, "%s%c", ap[i],
95 ap[i + 1] ? ' ' : '\n');
96 shf_flush(shl_out);
97 }
98 if (ap[0])
99 tp = findcom(ap[0], FC_BI|FC_FUNC);
100 }
101 flags &= ~XTIME;
102
103 if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
104 e->savefd = alloc(NUFILE * sizeof(short), ATEMP);
105 /* initialise to not redirected */
106 memset(e->savefd, 0, NUFILE * sizeof(short));
107 }
108
109 /* do redirection, to be restored in quitenv() */
110 if (t->ioact != NULL)
111 for (iowp = t->ioact; *iowp != NULL; iowp++) {
112 if (iosetup(*iowp, tp) < 0) {
113 exstat = rv = 1;
114 /* Redirection failures for special commands
115 * cause (non-interactive) shell to exit.
116 */
117 if (tp && tp->type == CSHELL &&
118 (tp->flag & SPEC_BI))
119 errorfz();
120 /* Deal with FERREXIT, quitenv(), etc. */
121 goto Break;
122 }
123 }
124
125 switch (t->type) {
126 case TCOM:
127 rv = comexec(t, tp, (const char **)ap, flags, xerrok);
128 break;
129
130 case TPAREN:
131 rv = execute(t->left, flags | XFORK, xerrok);
132 break;
133
134 case TPIPE:
135 flags |= XFORK;
136 flags &= ~XEXEC;
137 e->savefd[0] = savefd(0);
138 e->savefd[1] = savefd(1);
139 while (t->type == TPIPE) {
140 openpipe(pv);
141 ksh_dup2(pv[1], 1, false); /* stdout of curr */
142 /**
143 * Let exchild() close pv[0] in child
144 * (if this isn't done, commands like
145 * (: ; cat /etc/termcap) | sleep 1
146 * will hang forever).
147 */
148 exchild(t->left, flags | XPIPEO | XCCLOSE,
149 NULL, pv[0]);
150 ksh_dup2(pv[0], 0, false); /* stdin of next */
151 closepipe(pv);
152 flags |= XPIPEI;
153 t = t->right;
154 }
155 restfd(1, e->savefd[1]); /* stdout of last */
156 e->savefd[1] = 0; /* no need to re-restore this */
157 /* Let exchild() close 0 in parent, after fork, before wait */
158 i = exchild(t, flags | XPCLOSE, xerrok, 0);
159 if (!(flags&XBGND) && !(flags&XXCOM))
160 rv = i;
161 break;
162
163 case TLIST:
164 while (t->type == TLIST) {
165 execute(t->left, flags & XERROK, NULL);
166 t = t->right;
167 }
168 rv = execute(t, flags & XERROK, xerrok);
169 break;
170
171 case TCOPROC: {
172 sigset_t omask;
173
174 /* Block sigchild as we are using things changed in the
175 * signal handler
176 */
177 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
178 e->type = E_ERRH;
179 i = sigsetjmp(e->jbuf, 0);
180 if (i) {
181 sigprocmask(SIG_SETMASK, &omask, NULL);
182 quitenv(NULL);
183 unwind(i);
184 /* NOTREACHED */
185 }
186 /* Already have a (live) co-process? */
187 if (coproc.job && coproc.write >= 0)
188 errorf("coprocess already exists");
189
190 /* Can we re-use the existing co-process pipe? */
191 coproc_cleanup(true);
192
193 /* do this before opening pipes, in case these fail */
194 e->savefd[0] = savefd(0);
195 e->savefd[1] = savefd(1);
196
197 openpipe(pv);
198 if (pv[0] != 0) {
199 ksh_dup2(pv[0], 0, false);
200 close(pv[0]);
201 }
202 coproc.write = pv[1];
203 coproc.job = NULL;
204
205 if (coproc.readw >= 0)
206 ksh_dup2(coproc.readw, 1, false);
207 else {
208 openpipe(pv);
209 coproc.read = pv[0];
210 ksh_dup2(pv[1], 1, false);
211 coproc.readw = pv[1]; /* closed before first read */
212 coproc.njobs = 0;
213 /* create new coprocess id */
214 ++coproc.id;
215 }
216 sigprocmask(SIG_SETMASK, &omask, NULL);
217 e->type = E_EXEC; /* no more need for error handler */
218
219 /* exchild() closes coproc.* in child after fork,
220 * will also increment coproc.njobs when the
221 * job is actually created.
222 */
223 flags &= ~XEXEC;
224 exchild(t->left, flags | XBGND | XFORK | XCOPROC | XCCLOSE,
225 NULL, coproc.readw);
226 break;
227 }
228
229 case TASYNC:
230 /* XXX non-optimal, I think - "(foo &)", forks for (),
231 * forks again for async... parent should optimise
232 * this to "foo &"...
233 */
234 rv = execute(t->left, (flags&~XEXEC)|XBGND|XFORK, xerrok);
235 break;
236
237 case TOR:
238 case TAND:
239 rv = execute(t->left, XERROK, xerrok);
240 if ((rv == 0) == (t->type == TAND))
241 rv = execute(t->right, XERROK, xerrok);
242 flags |= XERROK;
243 if (xerrok)
244 *xerrok = 1;
245 break;
246
247 case TBANG:
248 rv = !execute(t->right, XERROK, xerrok);
249 flags |= XERROK;
250 if (xerrok)
251 *xerrok = 1;
252 break;
253
254 case TDBRACKET: {
255 Test_env te;
256
257 te.flags = TEF_DBRACKET;
258 te.pos.wp = t->args;
259 te.isa = dbteste_isa;
260 te.getopnd = dbteste_getopnd;
261 te.eval = test_eval;
262 te.error = dbteste_error;
263
264 rv = test_parse(&te);
265 break;
266 }
267
268 case TFOR:
269 case TSELECT: {
270 volatile bool is_first = true;
271 ap = (t->vars == NULL) ? e->loc->argv + 1 :
272 (const char **)eval((const char **)t->vars,
273 DOBLANK | DOGLOB | DOTILDE);
274 e->type = E_LOOP;
275 while (1) {
276 i = sigsetjmp(e->jbuf, 0);
277 if (!i)
278 break;
279 if ((e->flags&EF_BRKCONT_PASS) ||
280 (i != LBREAK && i != LCONTIN)) {
281 quitenv(NULL);
282 unwind(i);
283 } else if (i == LBREAK) {
284 rv = 0;
285 goto Break;
286 }
287 }
288 rv = 0; /* in case of a continue */
289 if (t->type == TFOR) {
290 while (*ap != NULL) {
291 setstr(global(t->str), *ap++, KSH_UNWIND_ERROR);
292 rv = execute(t->left, flags & XERROK, xerrok);
293 }
294 } else { /* TSELECT */
295 for (;;) {
296 if (!(cp = do_selectargs(ap, is_first))) {
297 rv = 1;
298 break;
299 }
300 is_first = false;
301 setstr(global(t->str), cp, KSH_UNWIND_ERROR);
302 execute(t->left, flags & XERROK, xerrok);
303 }
304 }
305 break;
306 }
307
308 case TWHILE:
309 case TUNTIL:
310 e->type = E_LOOP;
311 while (1) {
312 i = sigsetjmp(e->jbuf, 0);
313 if (!i)
314 break;
315 if ((e->flags&EF_BRKCONT_PASS) ||
316 (i != LBREAK && i != LCONTIN)) {
317 quitenv(NULL);
318 unwind(i);
319 } else if (i == LBREAK) {
320 rv = 0;
321 goto Break;
322 }
323 }
324 rv = 0; /* in case of a continue */
325 while ((execute(t->left, XERROK, NULL) == 0) ==
326 (t->type == TWHILE))
327 rv = execute(t->right, flags & XERROK, xerrok);
328 break;
329
330 case TIF:
331 case TELIF:
332 if (t->right == NULL)
333 break; /* should be error */
334 rv = execute(t->left, XERROK, NULL) == 0 ?
335 execute(t->right->left, flags & XERROK, xerrok) :
336 execute(t->right->right, flags & XERROK, xerrok);
337 break;
338
339 case TCASE:
340 cp = evalstr(t->str, DOTILDE);
341 for (t = t->left; t != NULL && t->type == TPAT; t = t->right)
342 for (ap = (const char **)t->vars; *ap; ap++)
343 if ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
344 gmatchx(cp, s, false))
345 goto Found;
346 break;
347 Found:
348 rv = execute(t->left, flags & XERROK, xerrok);
349 break;
350
351 case TBRACE:
352 rv = execute(t->left, flags & XERROK, xerrok);
353 break;
354
355 case TFUNCT:
356 rv = define(t->str, t);
357 break;
358
359 case TTIME:
360 /* Clear XEXEC so nested execute() call doesn't exit
361 * (allows "ls -l | time grep foo").
362 */
363 rv = timex(t, flags & ~XEXEC, xerrok);
364 break;
365
366 case TEXEC: /* an eval'd TCOM */
367 s = t->args[0];
368 up = makenv();
369 restoresigs();
370 cleanup_proc_env();
371 {
372 union mksh_ccphack cargs;
373
374 cargs.ro = t->args;
375 execve(t->str, cargs.rw, up);
376 rv = errno;
377 }
378 if (rv == ENOEXEC)
379 scriptexec(t, (const char **)up);
380 else
381 errorf("%s: %s", s, strerror(rv));
382 }
383 Break:
384 exstat = rv;
385
386 quitenv(NULL); /* restores IO */
387 if ((flags&XEXEC))
388 unwind(LEXIT); /* exit child */
389 if (rv != 0 && !(flags & XERROK) &&
390 (xerrok == NULL || !*xerrok)) {
391 trapsig(SIGERR_);
392 if (Flag(FERREXIT))
393 unwind(LERROR);
394 }
395 return (rv);
396 }
397
398 /*
399 * execute simple command
400 */
401
402 static int
comexec(struct op * t,struct tbl * volatile tp,const char ** ap,volatile int flags,volatile int * xerrok)403 comexec(struct op *t, struct tbl *volatile tp, const char **ap,
404 volatile int flags, volatile int *xerrok)
405 {
406 int i;
407 volatile int rv = 0;
408 const char *cp;
409 const char **lastp;
410 static struct op texec; /* Must be static (XXX but why?) */
411 int type_flags;
412 int keepasn_ok;
413 int fcflags = FC_BI|FC_FUNC|FC_PATH;
414 bool bourne_function_call = false;
415 struct block *l_expand, *l_assign;
416
417 /* snag the last argument for $_ XXX not the same as AT&T ksh,
418 * which only seems to set $_ after a newline (but not in
419 * functions/dot scripts, but in interactive and script) -
420 * perhaps save last arg here and set it in shell()?.
421 */
422 if (Flag(FTALKING) && *(lastp = ap)) {
423 while (*++lastp)
424 ;
425 /* setstr() can't fail here */
426 setstr(typeset("_", LOCAL, 0, INTEGER, 0), *--lastp,
427 KSH_RETURN_ERROR);
428 }
429
430 /* Deal with the shell builtins builtin, exec and command since
431 * they can be followed by other commands. This must be done before
432 * we know if we should create a local block which must be done
433 * before we can do a path search (in case the assignments change
434 * PATH).
435 * Odd cases:
436 * FOO=bar exec >/dev/null FOO is kept but not exported
437 * FOO=bar exec foobar FOO is exported
438 * FOO=bar command exec >/dev/null FOO is neither kept nor exported
439 * FOO=bar command FOO is neither kept nor exported
440 * PATH=... foobar use new PATH in foobar search
441 */
442 keepasn_ok = 1;
443 while (tp && tp->type == CSHELL) {
444 fcflags = FC_BI|FC_FUNC|FC_PATH;/* undo effects of command */
445 if (tp->val.f == c_builtin) {
446 if ((cp = *++ap) == NULL) {
447 tp = NULL;
448 break;
449 }
450 tp = findcom(cp, FC_BI);
451 if (tp == NULL)
452 errorf("builtin: %s: not a builtin", cp);
453 continue;
454 } else if (tp->val.f == c_exec) {
455 if (ap[1] == NULL)
456 break;
457 ap++;
458 flags |= XEXEC;
459 } else if (tp->val.f == c_command) {
460 int optc, saw_p = 0;
461
462 /* Ugly dealing with options in two places (here and
463 * in c_command(), but such is life)
464 */
465 ksh_getopt_reset(&builtin_opt, 0);
466 while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
467 saw_p = 1;
468 if (optc != EOF)
469 break; /* command -vV or something */
470 /* don't look for functions */
471 fcflags = FC_BI|FC_PATH;
472 if (saw_p) {
473 if (Flag(FRESTRICTED)) {
474 warningf(true,
475 "command -p: restricted");
476 rv = 1;
477 goto Leave;
478 }
479 fcflags |= FC_DEFPATH;
480 }
481 ap += builtin_opt.optind;
482 /* POSIX says special builtins lose their status
483 * if accessed using command.
484 */
485 keepasn_ok = 0;
486 if (!ap[0]) {
487 /* ensure command with no args exits with 0 */
488 subst_exstat = 0;
489 break;
490 }
491 } else
492 break;
493 tp = findcom(ap[0], fcflags & (FC_BI|FC_FUNC));
494 }
495 l_expand = e->loc;
496 if (keepasn_ok && (!ap[0] || (tp && (tp->flag & KEEPASN))))
497 type_flags = 0;
498 else {
499 /* create new variable/function block */
500 newblock();
501 /* ksh functions don't keep assignments, POSIX functions do. */
502 if (keepasn_ok && tp && tp->type == CFUNC &&
503 !(tp->flag & FKSH)) {
504 bourne_function_call = true;
505 type_flags = EXPORT;
506 } else
507 type_flags = LOCAL|LOCAL_COPY|EXPORT;
508 }
509 l_assign = e->loc;
510 if (Flag(FEXPORT))
511 type_flags |= EXPORT;
512 for (i = 0; t->vars[i]; i++) {
513 /* do NOT lookup in the new var/fn block just created */
514 e->loc = l_expand;
515 cp = evalstr(t->vars[i], DOASNTILDE);
516 e->loc = l_assign;
517 /* but assign in there as usual */
518
519 if (Flag(FXTRACE)) {
520 if (i == 0)
521 shf_fprintf(shl_out, "%s",
522 substitute(str_val(global("PS4")), 0));
523 shf_fprintf(shl_out, "%s%c", cp,
524 t->vars[i + 1] ? ' ' : '\n');
525 if (!t->vars[i + 1])
526 shf_flush(shl_out);
527 }
528 typeset(cp, type_flags, 0, 0, 0);
529 if (bourne_function_call && !(type_flags & EXPORT))
530 typeset(cp, LOCAL|LOCAL_COPY|EXPORT, 0, 0, 0);
531 }
532
533 if ((cp = *ap) == NULL) {
534 rv = subst_exstat;
535 goto Leave;
536 } else if (!tp) {
537 if (Flag(FRESTRICTED) && vstrchr(cp, '/')) {
538 warningf(true, "%s: restricted", cp);
539 rv = 1;
540 goto Leave;
541 }
542 tp = findcom(cp, fcflags);
543 }
544
545 switch (tp->type) {
546 case CSHELL: /* shell built-in */
547 rv = call_builtin(tp, (const char **)ap);
548 break;
549
550 case CFUNC: { /* function call */
551 volatile unsigned char old_xflag;
552 volatile Tflag old_inuse;
553 const char *volatile old_kshname;
554
555 if (!(tp->flag & ISSET)) {
556 struct tbl *ftp;
557
558 if (!tp->u.fpath) {
559 if (tp->u2.errno_) {
560 warningf(true,
561 "%s: can't find function "
562 "definition file - %s",
563 cp, strerror(tp->u2.errno_));
564 rv = 126;
565 } else {
566 warningf(true,
567 "%s: can't find function "
568 "definition file", cp);
569 rv = 127;
570 }
571 break;
572 }
573 if (include(tp->u.fpath, 0, NULL, 0) < 0) {
574 rv = errno;
575 warningf(true,
576 "%s: can't open function definition file %s - %s",
577 cp, tp->u.fpath, strerror(rv));
578 rv = 127;
579 break;
580 }
581 if (!(ftp = findfunc(cp, hash(cp), false)) ||
582 !(ftp->flag & ISSET)) {
583 warningf(true,
584 "%s: function not defined by %s",
585 cp, tp->u.fpath);
586 rv = 127;
587 break;
588 }
589 tp = ftp;
590 }
591
592 /* ksh functions set $0 to function name, POSIX functions leave
593 * $0 unchanged.
594 */
595 old_kshname = kshname;
596 if (tp->flag & FKSH)
597 kshname = ap[0];
598 else
599 ap[0] = kshname;
600 e->loc->argv = ap;
601 for (i = 0; *ap++ != NULL; i++)
602 ;
603 e->loc->argc = i - 1;
604 /* ksh-style functions handle getopts sanely,
605 * Bourne/POSIX functions are insane...
606 */
607 if (tp->flag & FKSH) {
608 e->loc->flags |= BF_DOGETOPTS;
609 e->loc->getopts_state = user_opt;
610 getopts_reset(1);
611 }
612
613 old_xflag = Flag(FXTRACE);
614 Flag(FXTRACE) = tp->flag & TRACE ? 1 : 0;
615
616 old_inuse = tp->flag & FINUSE;
617 tp->flag |= FINUSE;
618
619 e->type = E_FUNC;
620 i = sigsetjmp(e->jbuf, 0);
621 if (i == 0) {
622 /* seems odd to pass XERROK here, but AT&T ksh does */
623 exstat = execute(tp->val.t, flags & XERROK, xerrok);
624 i = LRETURN;
625 }
626 kshname = old_kshname;
627 Flag(FXTRACE) = old_xflag;
628 tp->flag = (tp->flag & ~FINUSE) | old_inuse;
629 /* Were we deleted while executing? If so, free the execution
630 * tree. todo: Unfortunately, the table entry is never re-used
631 * until the lookup table is expanded.
632 */
633 if ((tp->flag & (FDELETE|FINUSE)) == FDELETE) {
634 if (tp->flag & ALLOC) {
635 tp->flag &= ~ALLOC;
636 tfree(tp->val.t, tp->areap);
637 }
638 tp->flag = 0;
639 }
640 switch (i) {
641 case LRETURN:
642 case LERROR:
643 rv = exstat;
644 break;
645 case LINTR:
646 case LEXIT:
647 case LLEAVE:
648 case LSHELL:
649 quitenv(NULL);
650 unwind(i);
651 /* NOTREACHED */
652 default:
653 quitenv(NULL);
654 internal_errorf("CFUNC %d", i);
655 }
656 break;
657 }
658
659 case CEXEC: /* executable command */
660 case CTALIAS: /* tracked alias */
661 if (!(tp->flag&ISSET)) {
662 /* errno_ will be set if the named command was found
663 * but could not be executed (permissions, no execute
664 * bit, directory, etc). Print out a (hopefully)
665 * useful error message and set the exit status to 126.
666 */
667 if (tp->u2.errno_) {
668 warningf(true, "%s: cannot execute - %s", cp,
669 strerror(tp->u2.errno_));
670 rv = 126; /* POSIX */
671 } else {
672 warningf(true, "%s: not found", cp);
673 rv = 127;
674 }
675 break;
676 }
677
678 /* set $_ to programme's full path */
679 /* setstr() can't fail here */
680 setstr(typeset("_", LOCAL|EXPORT, 0, INTEGER, 0),
681 tp->val.s, KSH_RETURN_ERROR);
682
683 if (flags&XEXEC) {
684 j_exit();
685 if (!(flags&XBGND)
686 #ifndef MKSH_UNEMPLOYED
687 || Flag(FMONITOR)
688 #endif
689 ) {
690 setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
691 setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
692 }
693 }
694
695 /* to fork we set up a TEXEC node and call execute */
696 texec.type = TEXEC;
697 texec.left = t; /* for tprint */
698 texec.str = tp->val.s;
699 texec.args = ap;
700 rv = exchild(&texec, flags, xerrok, -1);
701 break;
702 }
703 Leave:
704 if (flags & XEXEC) {
705 exstat = rv;
706 unwind(LLEAVE);
707 }
708 return (rv);
709 }
710
711 static void
scriptexec(struct op * tp,const char ** ap)712 scriptexec(struct op *tp, const char **ap)
713 {
714 const char *sh;
715 #ifndef MKSH_SMALL
716 unsigned char *cp;
717 char buf[64]; /* 64 == MAXINTERP in MirBSD <sys/param.h> */
718 int fd;
719 #endif
720 union mksh_ccphack args, cap;
721
722 sh = str_val(global("EXECSHELL"));
723 if (sh && *sh)
724 sh = search(sh, path, X_OK, NULL);
725 if (!sh || !*sh)
726 sh = MKSH_DEFAULT_EXECSHELL;
727
728 *tp->args-- = tp->str;
729
730 #ifndef MKSH_SMALL
731 if ((fd = open(tp->str, O_RDONLY)) >= 0) {
732 /* read first MAXINTERP octets from file */
733 if (read(fd, buf, sizeof(buf)) <= 0)
734 /* read error -> no good */
735 buf[0] = '\0';
736 close(fd);
737 /* scan for newline (or CR) or NUL _before_ end of buffer */
738 cp = (unsigned char *)buf;
739 while ((char *)cp < (buf + sizeof(buf)))
740 if (*cp == '\0' || *cp == '\n' || *cp == '\r') {
741 *cp = '\0';
742 break;
743 } else
744 ++cp;
745 /* if the shebang line is longer than MAXINTERP, bail out */
746 if ((char *)cp >= (buf + sizeof(buf)))
747 goto noshebang;
748 /* skip UTF-8 Byte Order Mark, if present */
749 cp = (unsigned char *)buf;
750 if ((cp[0] == 0xEF) && (cp[1] == 0xBB) && (cp[2] == 0xBF))
751 cp += 3;
752 /* bail out if read error (above) or no shebang */
753 if ((cp[0] != '#') || (cp[1] != '!'))
754 goto noshebang;
755 cp += 2;
756 /* skip whitespace before shell name */
757 while (*cp == ' ' || *cp == '\t')
758 ++cp;
759 /* just whitespace on the line? */
760 if (*cp == '\0')
761 goto noshebang;
762 /* no, we actually found an interpreter name */
763 sh = (char *)cp;
764 /* look for end of shell/interpreter name */
765 while (*cp != ' ' && *cp != '\t' && *cp != '\0')
766 ++cp;
767 /* any arguments? */
768 if (*cp) {
769 *cp++ = '\0';
770 /* skip spaces before arguments */
771 while (*cp == ' ' || *cp == '\t')
772 ++cp;
773 /* pass it all in ONE argument (historic reasons) */
774 if (*cp)
775 *tp->args-- = (char *)cp;
776 }
777 noshebang:
778 fd = buf[0] << 8 | buf[1];
779 if ((fd == /* OMAGIC */ 0407) ||
780 (fd == /* NMAGIC */ 0410) ||
781 (fd == /* ZMAGIC */ 0413) ||
782 (fd == /* QMAGIC */ 0314) ||
783 (fd == /* ECOFF_I386 */ 0x4C01) ||
784 (fd == /* ECOFF_M68K */ 0x0150 || fd == 0x5001) ||
785 (fd == /* ECOFF_SH */ 0x0500 || fd == 0x0005) ||
786 (fd == 0x7F45 && buf[2] == 'L' && buf[3] == 'F') ||
787 (fd == /* "MZ" */ 0x4D5A) ||
788 (fd == /* gzip */ 0x1F8B))
789 errorf("%s: not executable: magic %04X", tp->str, fd);
790 }
791 #endif
792 args.ro = tp->args;
793 *args.ro = sh;
794
795 cap.ro = ap;
796 execve(args.rw[0], args.rw, cap.rw);
797
798 /* report both the programme that was run and the bogus interpreter */
799 errorf("%s: %s: %s", tp->str, sh, strerror(errno));
800 }
801
802 int
shcomexec(const char ** wp)803 shcomexec(const char **wp)
804 {
805 struct tbl *tp;
806
807 tp = ktsearch(&builtins, *wp, hash(*wp));
808 if (tp == NULL)
809 internal_errorf("shcomexec: %s", *wp);
810 return (call_builtin(tp, wp));
811 }
812
813 /*
814 * Search function tables for a function. If create set, a table entry
815 * is created if none is found.
816 */
817 struct tbl *
findfunc(const char * name,uint32_t h,bool create)818 findfunc(const char *name, uint32_t h, bool create)
819 {
820 struct block *l;
821 struct tbl *tp = NULL;
822
823 for (l = e->loc; l; l = l->next) {
824 tp = ktsearch(&l->funs, name, h);
825 if (tp)
826 break;
827 if (!l->next && create) {
828 tp = ktenter(&l->funs, name, h);
829 tp->flag = DEFINED;
830 tp->type = CFUNC;
831 tp->val.t = NULL;
832 break;
833 }
834 }
835 return (tp);
836 }
837
838 /*
839 * define function. Returns 1 if function is being undefined (t == 0) and
840 * function did not exist, returns 0 otherwise.
841 */
842 int
define(const char * name,struct op * t)843 define(const char *name, struct op *t)
844 {
845 struct tbl *tp;
846 bool was_set = false;
847
848 while (1) {
849 tp = findfunc(name, hash(name), true);
850
851 if (tp->flag & ISSET)
852 was_set = true;
853 /* If this function is currently being executed, we zap this
854 * table entry so findfunc() won't see it
855 */
856 if (tp->flag & FINUSE) {
857 tp->name[0] = '\0';
858 tp->flag &= ~DEFINED; /* ensure it won't be found */
859 tp->flag |= FDELETE;
860 } else
861 break;
862 }
863
864 if (tp->flag & ALLOC) {
865 tp->flag &= ~(ISSET|ALLOC);
866 tfree(tp->val.t, tp->areap);
867 }
868
869 if (t == NULL) { /* undefine */
870 ktdelete(tp);
871 return (was_set ? 0 : 1);
872 }
873
874 tp->val.t = tcopy(t->left, tp->areap);
875 tp->flag |= (ISSET|ALLOC);
876 if (t->u.ksh_func)
877 tp->flag |= FKSH;
878
879 return (0);
880 }
881
882 /*
883 * add builtin
884 */
885 void
builtin(const char * name,int (* func)(const char **))886 builtin(const char *name, int (*func) (const char **))
887 {
888 struct tbl *tp;
889 Tflag flag;
890
891 /* see if any flags should be set for this builtin */
892 for (flag = 0; ; name++) {
893 if (*name == '=') /* command does variable assignment */
894 flag |= KEEPASN;
895 else if (*name == '*') /* POSIX special builtin */
896 flag |= SPEC_BI;
897 else if (*name == '+') /* POSIX regular builtin */
898 flag |= REG_BI;
899 else
900 break;
901 }
902
903 tp = ktenter(&builtins, name, hash(name));
904 tp->flag = DEFINED | flag;
905 tp->type = CSHELL;
906 tp->val.f = func;
907 }
908
909 /*
910 * find command
911 * either function, hashed command, or built-in (in that order)
912 */
913 struct tbl *
findcom(const char * name,int flags)914 findcom(const char *name, int flags)
915 {
916 static struct tbl temp;
917 uint32_t h = hash(name);
918 struct tbl *tp = NULL, *tbi;
919 unsigned char insert = Flag(FTRACKALL); /* insert if not found */
920 char *fpath; /* for function autoloading */
921 union mksh_cchack npath;
922
923 if (vstrchr(name, '/')) {
924 insert = 0;
925 /* prevent FPATH search below */
926 flags &= ~FC_FUNC;
927 goto Search;
928 }
929 tbi = (flags & FC_BI) ? ktsearch(&builtins, name, h) : NULL;
930 /* POSIX says special builtins first, then functions, then
931 * POSIX regular builtins, then search path...
932 */
933 if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
934 tp = tbi;
935 if (!tp && (flags & FC_FUNC)) {
936 tp = findfunc(name, h, false);
937 if (tp && !(tp->flag & ISSET)) {
938 if ((fpath = str_val(global("FPATH"))) == null) {
939 tp->u.fpath = NULL;
940 tp->u2.errno_ = 0;
941 } else
942 tp->u.fpath = search(name, fpath, R_OK,
943 &tp->u2.errno_);
944 }
945 }
946 if (!tp && (flags & FC_REGBI) && tbi && (tbi->flag & REG_BI))
947 tp = tbi;
948 if (!tp && (flags & FC_UNREGBI) && tbi)
949 tp = tbi;
950 if (!tp && (flags & FC_PATH) && !(flags & FC_DEFPATH)) {
951 tp = ktsearch(&taliases, name, h);
952 if (tp && (tp->flag & ISSET) && access(tp->val.s, X_OK) != 0) {
953 if (tp->flag & ALLOC) {
954 tp->flag &= ~ALLOC;
955 afree(tp->val.s, APERM);
956 }
957 tp->flag &= ~ISSET;
958 }
959 }
960
961 Search:
962 if ((!tp || (tp->type == CTALIAS && !(tp->flag&ISSET))) &&
963 (flags & FC_PATH)) {
964 if (!tp) {
965 if (insert && !(flags & FC_DEFPATH)) {
966 tp = ktenter(&taliases, name, h);
967 tp->type = CTALIAS;
968 } else {
969 tp = &temp;
970 tp->type = CEXEC;
971 }
972 tp->flag = DEFINED; /* make ~ISSET */
973 }
974 npath.ro = search(name, flags & FC_DEFPATH ? def_path : path,
975 X_OK, &tp->u2.errno_);
976 if (npath.ro) {
977 strdupx(tp->val.s, npath.ro, APERM);
978 if (npath.ro != name)
979 afree(npath.rw, ATEMP);
980 tp->flag |= ISSET|ALLOC;
981 } else if ((flags & FC_FUNC) &&
982 (fpath = str_val(global("FPATH"))) != null &&
983 (npath.ro = search(name, fpath, R_OK,
984 &tp->u2.errno_)) != NULL) {
985 /* An undocumented feature of AT&T ksh is that it
986 * searches FPATH if a command is not found, even
987 * if the command hasn't been set up as an autoloaded
988 * function (ie, no typeset -uf).
989 */
990 tp = &temp;
991 tp->type = CFUNC;
992 tp->flag = DEFINED; /* make ~ISSET */
993 tp->u.fpath = npath.ro;
994 }
995 }
996 return (tp);
997 }
998
999 /*
1000 * flush executable commands with relative paths
1001 */
1002 void
flushcom(int all)1003 flushcom(int all) /* just relative or all */
1004 {
1005 struct tbl *tp;
1006 struct tstate ts;
1007
1008 for (ktwalk(&ts, &taliases); (tp = ktnext(&ts)) != NULL; )
1009 if ((tp->flag&ISSET) && (all || tp->val.s[0] != '/')) {
1010 if (tp->flag&ALLOC) {
1011 tp->flag &= ~(ALLOC|ISSET);
1012 afree(tp->val.s, APERM);
1013 }
1014 tp->flag &= ~ISSET;
1015 }
1016 }
1017
1018 /* Check if path is something we want to find. Returns -1 for failure. */
1019 int
search_access(const char * lpath,int mode,int * errnop)1020 search_access(const char *lpath, int mode,
1021 int *errnop) /* set if candidate found, but not suitable */
1022 {
1023 int ret, err = 0;
1024 struct stat statb;
1025
1026 if (stat(lpath, &statb) < 0)
1027 return (-1);
1028 ret = access(lpath, mode);
1029 if (ret < 0)
1030 err = errno; /* File exists, but we can't access it */
1031 else if (mode == X_OK && (!S_ISREG(statb.st_mode) ||
1032 !(statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)))) {
1033 /* This 'cause access() says root can execute everything */
1034 ret = -1;
1035 err = S_ISDIR(statb.st_mode) ? EISDIR : EACCES;
1036 }
1037 if (err && errnop && !*errnop)
1038 *errnop = err;
1039 return (ret);
1040 }
1041
1042 /*
1043 * search for command with PATH
1044 */
1045 const char *
search(const char * name,const char * lpath,int mode,int * errnop)1046 search(const char *name, const char *lpath,
1047 int mode, /* R_OK or X_OK */
1048 int *errnop) /* set if candidate found, but not suitable */
1049 {
1050 const char *sp, *p;
1051 char *xp;
1052 XString xs;
1053 int namelen;
1054
1055 if (errnop)
1056 *errnop = 0;
1057 if (vstrchr(name, '/')) {
1058 if (search_access(name, mode, errnop) == 0)
1059 return (name);
1060 return (NULL);
1061 }
1062
1063 namelen = strlen(name) + 1;
1064 Xinit(xs, xp, 128, ATEMP);
1065
1066 sp = lpath;
1067 while (sp != NULL) {
1068 xp = Xstring(xs, xp);
1069 if (!(p = cstrchr(sp, ':')))
1070 p = sp + strlen(sp);
1071 if (p != sp) {
1072 XcheckN(xs, xp, p - sp);
1073 memcpy(xp, sp, p - sp);
1074 xp += p - sp;
1075 *xp++ = '/';
1076 }
1077 sp = p;
1078 XcheckN(xs, xp, namelen);
1079 memcpy(xp, name, namelen);
1080 if (search_access(Xstring(xs, xp), mode, errnop) == 0)
1081 return (Xclose(xs, xp + namelen));
1082 if (*sp++ == '\0')
1083 sp = NULL;
1084 }
1085 Xfree(xs, xp);
1086 return (NULL);
1087 }
1088
1089 static int
call_builtin(struct tbl * tp,const char ** wp)1090 call_builtin(struct tbl *tp, const char **wp)
1091 {
1092 int rv;
1093
1094 builtin_argv0 = wp[0];
1095 builtin_flag = tp->flag;
1096 shf_reopen(1, SHF_WR, shl_stdout);
1097 shl_stdout_ok = 1;
1098 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1099 rv = (*tp->val.f)(wp);
1100 shf_flush(shl_stdout);
1101 shl_stdout_ok = 0;
1102 builtin_flag = 0;
1103 builtin_argv0 = NULL;
1104 return (rv);
1105 }
1106
1107 /*
1108 * set up redirection, saving old fds in e->savefd
1109 */
1110 static int
iosetup(struct ioword * iop,struct tbl * tp)1111 iosetup(struct ioword *iop, struct tbl *tp)
1112 {
1113 int u = -1;
1114 char *cp = iop->name;
1115 int iotype = iop->flag & IOTYPE;
1116 int do_open = 1, do_close = 0, flags = 0;
1117 struct ioword iotmp;
1118 struct stat statb;
1119
1120 if (iotype != IOHERE)
1121 cp = evalonestr(cp, DOTILDE|(Flag(FTALKING_I) ? DOGLOB : 0));
1122
1123 /* Used for tracing and error messages to print expanded cp */
1124 iotmp = *iop;
1125 iotmp.name = (iotype == IOHERE) ? NULL : cp;
1126 iotmp.flag |= IONAMEXP;
1127
1128 if (Flag(FXTRACE))
1129 shellf("%s%s\n",
1130 substitute(str_val(global("PS4")), 0),
1131 snptreef(NULL, 32, "%R", &iotmp));
1132
1133 switch (iotype) {
1134 case IOREAD:
1135 flags = O_RDONLY;
1136 break;
1137
1138 case IOCAT:
1139 flags = O_WRONLY | O_APPEND | O_CREAT;
1140 break;
1141
1142 case IOWRITE:
1143 flags = O_WRONLY | O_CREAT | O_TRUNC;
1144 /* The stat() is here to allow redirections to
1145 * things like /dev/null without error.
1146 */
1147 if (Flag(FNOCLOBBER) && !(iop->flag & IOCLOB) &&
1148 (stat(cp, &statb) < 0 || S_ISREG(statb.st_mode)))
1149 flags |= O_EXCL;
1150 break;
1151
1152 case IORDWR:
1153 flags = O_RDWR | O_CREAT;
1154 break;
1155
1156 case IOHERE:
1157 do_open = 0;
1158 /* herein() returns -2 if error has been printed */
1159 u = herein(iop->heredoc, iop->flag & IOEVAL);
1160 /* cp may have wrong name */
1161 break;
1162
1163 case IODUP: {
1164 const char *emsg;
1165
1166 do_open = 0;
1167 if (*cp == '-' && !cp[1]) {
1168 u = 1009; /* prevent error return below */
1169 do_close = 1;
1170 } else if ((u = check_fd(cp,
1171 X_OK | ((iop->flag & IORDUP) ? R_OK : W_OK),
1172 &emsg)) < 0) {
1173 warningf(true, "%s: %s",
1174 snptreef(NULL, 32, "%R", &iotmp), emsg);
1175 return (-1);
1176 }
1177 if (u == iop->unit)
1178 return (0); /* "dup from" == "dup to" */
1179 break;
1180 }
1181 }
1182
1183 if (do_open) {
1184 if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
1185 warningf(true, "%s: restricted", cp);
1186 return (-1);
1187 }
1188 u = open(cp, flags, 0666);
1189 }
1190 if (u < 0) {
1191 /* herein() may already have printed message */
1192 if (u == -1) {
1193 u = errno;
1194 warningf(true, "cannot %s %s: %s",
1195 iotype == IODUP ? "dup" :
1196 (iotype == IOREAD || iotype == IOHERE) ?
1197 "open" : "create", cp, strerror(u));
1198 }
1199 return (-1);
1200 }
1201 /* Do not save if it has already been redirected (i.e. "cat >x >y"). */
1202 if (e->savefd[iop->unit] == 0) {
1203 /* If these are the same, it means unit was previously closed */
1204 if (u == iop->unit)
1205 e->savefd[iop->unit] = -1;
1206 else
1207 /* c_exec() assumes e->savefd[fd] set for any
1208 * redirections. Ask savefd() not to close iop->unit;
1209 * this allows error messages to be seen if iop->unit
1210 * is 2; also means we can't lose the fd (eg, both
1211 * dup2 below and dup2 in restfd() failing).
1212 */
1213 e->savefd[iop->unit] = savefd(iop->unit);
1214 }
1215
1216 if (do_close)
1217 close(iop->unit);
1218 else if (u != iop->unit) {
1219 if (ksh_dup2(u, iop->unit, true) < 0) {
1220 int ev;
1221
1222 ev = errno;
1223 warningf(true,
1224 "could not finish (dup) redirection %s: %s",
1225 snptreef(NULL, 32, "%R", &iotmp),
1226 strerror(ev));
1227 if (iotype != IODUP)
1228 close(u);
1229 return (-1);
1230 }
1231 if (iotype != IODUP)
1232 close(u);
1233 /* Touching any co-process fd in an empty exec
1234 * causes the shell to close its copies
1235 */
1236 else if (tp && tp->type == CSHELL && tp->val.f == c_exec) {
1237 if (iop->flag & IORDUP) /* possible exec <&p */
1238 coproc_read_close(u);
1239 else /* possible exec >&p */
1240 coproc_write_close(u);
1241 }
1242 }
1243 if (u == 2) /* Clear any write errors */
1244 shf_reopen(2, SHF_WR, shl_out);
1245 return (0);
1246 }
1247
1248 /*
1249 * open here document temp file.
1250 * if unquoted here, expand here temp file into second temp file.
1251 */
1252 static int
herein(const char * content,int sub)1253 herein(const char *content, int sub)
1254 {
1255 volatile int fd = -1;
1256 struct source *s, *volatile osource;
1257 struct shf *volatile shf;
1258 struct temp *h;
1259 int i;
1260
1261 /* ksh -c 'cat << EOF' can cause this... */
1262 if (content == NULL) {
1263 warningf(true, "here document missing");
1264 return (-2); /* special to iosetup(): don't print error */
1265 }
1266
1267 /* Create temp file to hold content (done before newenv so temp
1268 * doesn't get removed too soon).
1269 */
1270 h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
1271 if (!(shf = h->shf) || (fd = open(h->name, O_RDONLY, 0)) < 0) {
1272 fd = errno;
1273 warningf(true, "can't %s temporary file %s: %s",
1274 !shf ? "create" : "open",
1275 h->name, strerror(fd));
1276 if (shf)
1277 shf_close(shf);
1278 return (-2 /* special to iosetup(): don't print error */);
1279 }
1280
1281 osource = source;
1282 newenv(E_ERRH);
1283 i = sigsetjmp(e->jbuf, 0);
1284 if (i) {
1285 source = osource;
1286 quitenv(shf);
1287 close(fd);
1288 return (-2); /* special to iosetup(): don't print error */
1289 }
1290 if (sub) {
1291 /* Do substitutions on the content of heredoc */
1292 s = pushs(SSTRING, ATEMP);
1293 s->start = s->str = content;
1294 source = s;
1295 if (yylex(ONEWORD|HEREDOC) != LWORD)
1296 internal_errorf("herein: yylex");
1297 source = osource;
1298 shf_puts(evalstr(yylval.cp, 0), shf);
1299 } else
1300 shf_puts(content, shf);
1301
1302 quitenv(NULL);
1303
1304 if (shf_close(shf) == EOF) {
1305 i = errno;
1306 close(fd);
1307 fd = errno;
1308 warningf(true, "error writing %s: %s, %s", h->name,
1309 strerror(i), strerror(fd));
1310 return (-2); /* special to iosetup(): don't print error */
1311 }
1312
1313 return (fd);
1314 }
1315
1316 /*
1317 * ksh special - the select command processing section
1318 * print the args in column form - assuming that we can
1319 */
1320 static const char *
do_selectargs(const char ** ap,bool print_menu)1321 do_selectargs(const char **ap, bool print_menu)
1322 {
1323 static const char *read_args[] = {
1324 "read", "-r", "REPLY", NULL
1325 };
1326 char *s;
1327 int i, argct;
1328
1329 for (argct = 0; ap[argct]; argct++)
1330 ;
1331 while (1) {
1332 /* Menu is printed if
1333 * - this is the first time around the select loop
1334 * - the user enters a blank line
1335 * - the REPLY parameter is empty
1336 */
1337 if (print_menu || !*str_val(global("REPLY")))
1338 pr_menu(ap);
1339 shellf("%s", str_val(global("PS3")));
1340 if (call_builtin(findcom("read", FC_BI), read_args))
1341 return (NULL);
1342 s = str_val(global("REPLY"));
1343 if (*s) {
1344 getn(s, &i);
1345 return ((i >= 1 && i <= argct) ? ap[i - 1] : null);
1346 }
1347 print_menu = 1;
1348 }
1349 }
1350
1351 struct select_menu_info {
1352 const char * const *args;
1353 int num_width;
1354 };
1355
1356 static char *select_fmt_entry(char *, int, int, const void *);
1357
1358 /* format a single select menu item */
1359 static char *
select_fmt_entry(char * buf,int buflen,int i,const void * arg)1360 select_fmt_entry(char *buf, int buflen, int i, const void *arg)
1361 {
1362 const struct select_menu_info *smi =
1363 (const struct select_menu_info *)arg;
1364
1365 shf_snprintf(buf, buflen, "%*d) %s",
1366 smi->num_width, i + 1, smi->args[i]);
1367 return (buf);
1368 }
1369
1370 /*
1371 * print a select style menu
1372 */
1373 int
pr_menu(const char * const * ap)1374 pr_menu(const char * const *ap)
1375 {
1376 struct select_menu_info smi;
1377 const char * const *pp;
1378 int acols = 0, aocts = 0, i, n;
1379
1380 /*
1381 * width/column calculations were done once and saved, but this
1382 * means select can't be used recursively so we re-calculate
1383 * each time (could save in a structure that is returned, but
1384 * it's probably not worth the bother)
1385 */
1386
1387 /*
1388 * get dimensions of the list
1389 */
1390 for (n = 0, pp = ap; *pp; n++, pp++) {
1391 i = strlen(*pp);
1392 if (i > aocts)
1393 aocts = i;
1394 i = utf_mbswidth(*pp);
1395 if (i > acols)
1396 acols = i;
1397 }
1398
1399 /*
1400 * we will print an index of the form "%d) " in front of
1401 * each entry, so get the maximum width of this
1402 */
1403 for (i = n, smi.num_width = 1; i >= 10; i /= 10)
1404 smi.num_width++;
1405
1406 smi.args = ap;
1407 print_columns(shl_out, n, select_fmt_entry, (void *)&smi,
1408 smi.num_width + 2 + aocts, smi.num_width + 2 + acols,
1409 true);
1410
1411 return (n);
1412 }
1413
1414 /* XXX: horrible kludge to fit within the framework */
1415 static char *plain_fmt_entry(char *, int, int, const void *);
1416
1417 static char *
plain_fmt_entry(char * buf,int buflen,int i,const void * arg)1418 plain_fmt_entry(char *buf, int buflen, int i, const void *arg)
1419 {
1420 shf_snprintf(buf, buflen, "%s", ((const char * const *)arg)[i]);
1421 return (buf);
1422 }
1423
1424 int
pr_list(char * const * ap)1425 pr_list(char * const *ap)
1426 {
1427 int acols = 0, aocts = 0, i, n;
1428 char * const *pp;
1429
1430 for (n = 0, pp = ap; *pp; n++, pp++) {
1431 i = strlen(*pp);
1432 if (i > aocts)
1433 aocts = i;
1434 i = utf_mbswidth(*pp);
1435 if (i > acols)
1436 acols = i;
1437 }
1438
1439 print_columns(shl_out, n, plain_fmt_entry, (const void *)ap,
1440 aocts, acols, false);
1441
1442 return (n);
1443 }
1444
1445 /*
1446 * [[ ... ]] evaluation routines
1447 */
1448
1449 /*
1450 * Test if the current token is a whatever. Accepts the current token if
1451 * it is. Returns 0 if it is not, non-zero if it is (in the case of
1452 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
1453 */
1454 static Test_op
dbteste_isa(Test_env * te,Test_meta meta)1455 dbteste_isa(Test_env *te, Test_meta meta)
1456 {
1457 Test_op ret = TO_NONOP;
1458 int uqword;
1459 const char *p;
1460
1461 if (!*te->pos.wp)
1462 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
1463
1464 /* unquoted word? */
1465 for (p = *te->pos.wp; *p == CHAR; p += 2)
1466 ;
1467 uqword = *p == EOS;
1468
1469 if (meta == TM_UNOP || meta == TM_BINOP) {
1470 if (uqword) {
1471 char buf[8]; /* longer than the longest operator */
1472 char *q = buf;
1473 for (p = *te->pos.wp;
1474 *p == CHAR && q < &buf[sizeof(buf) - 1]; p += 2)
1475 *q++ = p[1];
1476 *q = '\0';
1477 ret = test_isop(meta, buf);
1478 }
1479 } else if (meta == TM_END)
1480 ret = TO_NONOP;
1481 else
1482 ret = (uqword && !strcmp(*te->pos.wp,
1483 dbtest_tokens[(int)meta])) ? TO_NONNULL : TO_NONOP;
1484
1485 /* Accept the token? */
1486 if (ret != TO_NONOP)
1487 te->pos.wp++;
1488
1489 return (ret);
1490 }
1491
1492 static const char *
dbteste_getopnd(Test_env * te,Test_op op,bool do_eval)1493 dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
1494 {
1495 const char *s = *te->pos.wp;
1496
1497 if (!s)
1498 return (NULL);
1499
1500 te->pos.wp++;
1501
1502 if (!do_eval)
1503 return (null);
1504
1505 if (op == TO_STEQL || op == TO_STNEQ)
1506 s = evalstr(s, DOTILDE | DOPAT);
1507 else
1508 s = evalstr(s, DOTILDE);
1509
1510 return (s);
1511 }
1512
1513 static void
dbteste_error(Test_env * te,int offset,const char * msg)1514 dbteste_error(Test_env *te, int offset, const char *msg)
1515 {
1516 te->flags |= TEF_ERROR;
1517 internal_warningf("dbteste_error: %s (offset %d)", msg, offset);
1518 }
1519