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