1/* 2 * exec.c - command execution 3 * 4 * This file is part of zsh, the Z shell. 5 * 6 * Copyright (c) 1992-1997 Paul Falstad 7 * All rights reserved. 8 * 9 * Permission is hereby granted, without written agreement and without 10 * license or royalty fees, to use, copy, modify, and distribute this 11 * software and to distribute modified versions of this software for any 12 * purpose, provided that the above copyright notice and the following 13 * two paragraphs appear in all copies of this software. 14 * 15 * In no event shall Paul Falstad or the Zsh Development Group be liable 16 * to any party for direct, indirect, special, incidental, or consequential 17 * damages arising out of the use of this software and its documentation, 18 * even if Paul Falstad and the Zsh Development Group have been advised of 19 * the possibility of such damage. 20 * 21 * Paul Falstad and the Zsh Development Group specifically disclaim any 22 * warranties, including, but not limited to, the implied warranties of 23 * merchantability and fitness for a particular purpose. The software 24 * provided hereunder is on an "as is" basis, and Paul Falstad and the 25 * Zsh Development Group have no obligation to provide maintenance, 26 * support, updates, enhancements, or modifications. 27 * 28 */ 29 30#include "zsh.mdh" 31#include "exec.pro" 32 33/* Flags for last argument of addvars */ 34 35enum { 36 /* Export the variable for "VAR=val cmd ..." */ 37 ADDVAR_EXPORT = 1 << 0, 38 /* Apply restrictions for variable */ 39 ADDVAR_RESTRICT = 1 << 1, 40 /* Variable list is being restored later */ 41 ADDVAR_RESTORE = 1 << 2 42}; 43 44/* used to suppress ERREXIT and trapping of SIGZERR, SIGEXIT. */ 45 46/**/ 47int noerrexit; 48 49/* 50 * noerrs = 1: suppress error messages 51 * noerrs = 2: don't set errflag on parse error, either 52 */ 53 54/**/ 55mod_export int noerrs; 56 57/* do not save history on exec and exit */ 58 59/**/ 60int nohistsave; 61 62/* error/break flag */ 63 64/**/ 65mod_export int errflag; 66 67/* 68 * State of trap return value. Value is from enum trap_state. 69 */ 70 71/**/ 72int trap_state; 73 74/* 75 * Value associated with return from a trap. 76 * This is only active if we are inside a trap, else its value 77 * is irrelevant. It is initialised to -1 for a function trap and 78 * -2 for a non-function trap and if negative is decremented as 79 * we go deeper into functions and incremented as we come back up. 80 * The value is used to decide if an explicit "return" should cause 81 * a return from the caller of the trap; it does this by setting 82 * trap_return to a status (i.e. a non-negative value). 83 * 84 * In summary, trap_return is 85 * - zero unless we are in a trap 86 * - negative in a trap unless it has triggered. Code uses this 87 * to detect an active trap. 88 * - non-negative in a trap once it was triggered. It should remain 89 * non-negative until restored after execution of the trap. 90 */ 91 92/**/ 93int trap_return; 94 95/* != 0 if this is a subshell */ 96 97/**/ 98int subsh; 99 100/* != 0 if we have a return pending */ 101 102/**/ 103mod_export int retflag; 104 105/**/ 106long lastval2; 107 108/* The table of file descriptors. A table element is zero if the * 109 * corresponding fd is not used by the shell. It is greater than * 110 * 1 if the fd is used by a <(...) or >(...) substitution and 1 if * 111 * it is an internal file descriptor which must be closed before * 112 * executing an external command. The first ten elements of the * 113 * table is not used. A table element is set by movefd and cleard * 114 * by zclose. */ 115 116/**/ 117mod_export unsigned char *fdtable; 118 119/* The allocated size of fdtable */ 120 121/**/ 122int fdtable_size; 123 124/* The highest fd that marked with nonzero in fdtable */ 125 126/**/ 127mod_export int max_zsh_fd; 128 129/* input fd from the coprocess */ 130 131/**/ 132mod_export int coprocin; 133 134/* output fd from the coprocess */ 135 136/**/ 137mod_export int coprocout; 138 139/* count of file locks recorded in fdtable */ 140 141/**/ 142int fdtable_flocks; 143 144 145/* != 0 if the line editor is active */ 146 147/**/ 148mod_export int zleactive; 149 150/* pid of process undergoing 'process substitution' */ 151 152/**/ 153pid_t cmdoutpid; 154 155/* exit status of process undergoing 'process substitution' */ 156 157/**/ 158int cmdoutval; 159 160/* 161 * This is set by an exiting $(...) substitution to indicate we need 162 * to retain the status. We initialize it to zero if we think we need 163 * to reset the status for a command. 164 */ 165 166/**/ 167int use_cmdoutval; 168 169/* The context in which a shell function is called, see SFC_* in zsh.h. */ 170 171/**/ 172mod_export int sfcontext; 173 174/* Stack to save some variables before executing a signal handler function */ 175 176/**/ 177struct execstack *exstack; 178 179/* Stack with names of functions currently active. */ 180 181/**/ 182mod_export Funcstack funcstack; 183 184#define execerr() \ 185 do { \ 186 if (!forked) { \ 187 redir_err = lastval = 1; \ 188 goto done; \ 189 } else { \ 190 _exit(1); \ 191 } \ 192 } while (0) 193 194static int doneps4; 195static char *STTYval; 196static char *blank_env[] = { NULL }; 197 198/* Execution functions. */ 199 200static int (*execfuncs[WC_COUNT-WC_CURSH]) _((Estate, int)) = { 201 execcursh, exectime, execfuncdef, execfor, execselect, 202 execwhile, execrepeat, execcase, execif, execcond, 203 execarith, execautofn, exectry 204}; 205 206/* structure for command builtin for when it is used with -v or -V */ 207static struct builtin commandbn = 208 BUILTIN(0, 0, bin_whence, 0, -1, BIN_COMMAND, "vV", NULL); 209 210/* parse string into a list */ 211 212/**/ 213mod_export Eprog 214parse_string(char *s, int reset_lineno) 215{ 216 Eprog p; 217 zlong oldlineno; 218 219 lexsave(); 220 inpush(s, INP_LINENO, NULL); 221 strinbeg(0); 222 oldlineno = lineno; 223 if (reset_lineno) 224 lineno = 1; 225 p = parse_list(); 226 lineno = oldlineno; 227 if (tok == LEXERR && !lastval) 228 lastval = 1; 229 strinend(); 230 inpop(); 231 lexrestore(); 232 return p; 233} 234 235/**/ 236#ifdef HAVE_GETRLIMIT 237 238/* the resource limits for the shell and its children */ 239 240/**/ 241mod_export struct rlimit current_limits[RLIM_NLIMITS], limits[RLIM_NLIMITS]; 242 243/**/ 244mod_export int 245zsetlimit(int limnum, char *nam) 246{ 247 if (limits[limnum].rlim_max != current_limits[limnum].rlim_max || 248 limits[limnum].rlim_cur != current_limits[limnum].rlim_cur) { 249 if (setrlimit(limnum, limits + limnum)) { 250 if (nam) 251 zwarnnam(nam, "setrlimit failed: %e", errno); 252 return -1; 253 } 254 current_limits[limnum] = limits[limnum]; 255 } 256 return 0; 257} 258 259/**/ 260mod_export int 261setlimits(char *nam) 262{ 263 int limnum; 264 int ret = 0; 265 266 for (limnum = 0; limnum < RLIM_NLIMITS; limnum++) 267 if (zsetlimit(limnum, nam)) 268 ret++; 269 return ret; 270} 271 272/**/ 273#endif /* HAVE_GETRLIMIT */ 274 275/* fork and set limits */ 276 277/**/ 278static pid_t 279zfork(struct timeval *tv) 280{ 281 pid_t pid; 282 struct timezone dummy_tz; 283 284 /* 285 * Is anybody willing to explain this test? 286 */ 287 if (thisjob != -1 && thisjob >= jobtabsize - 1 && !expandjobtab()) { 288 zerr("job table full"); 289 return -1; 290 } 291 if (tv) 292 gettimeofday(tv, &dummy_tz); 293 /* 294 * Queueing signals is necessary on Linux because fork() 295 * manipulates mutexes, leading to deadlock in memory 296 * allocation. We don't expect fork() to be particularly 297 * zippy anyway. 298 */ 299 queue_signals(); 300 pid = fork(); 301 unqueue_signals(); 302 if (pid == -1) { 303 zerr("fork failed: %e", errno); 304 return -1; 305 } 306#ifdef HAVE_GETRLIMIT 307 if (!pid) 308 /* set resource limits for the child process */ 309 setlimits(NULL); 310#endif 311 return pid; 312} 313 314/* 315 * Allen Edeln gebiet ich Andacht, 316 * Hohen und Niedern von Heimdalls Geschlecht; 317 * Ich will list_pipe's Wirken kuenden 318 * Die aeltesten Sagen, der ich mich entsinne... 319 * 320 * In most shells, if you do something like: 321 * 322 * cat foo | while read a; do grep $a bar; done 323 * 324 * the shell forks and executes the loop in the sub-shell thus created. 325 * In zsh this traditionally executes the loop in the current shell, which 326 * is nice to have if the loop does something to change the shell, like 327 * setting parameters or calling builtins. 328 * Putting the loop in a sub-shell makes life easy, because the shell only 329 * has to put it into the job-structure and then treats it as a normal 330 * process. Suspending and interrupting is no problem then. 331 * Some years ago, zsh either couldn't suspend such things at all, or 332 * it got really messed up when users tried to do it. As a solution, we 333 * implemented the list_pipe-stuff, which has since then become a reason 334 * for many nightmares. 335 * Pipelines like the one above are executed by the functions in this file 336 * which call each other (and sometimes recursively). The one above, for 337 * example would lead to a function call stack roughly like: 338 * 339 * execlist->execpline->execcmd->execwhile->execlist->execpline 340 * 341 * (when waiting for the grep, ignoring execpline2 for now). At this time, 342 * zsh has built two job-table entries for it: one for the cat and one for 343 * the grep. If the user hits ^Z at this point (and jobbing is used), the 344 * shell is notified that the grep was suspended. The list_pipe flag is 345 * used to tell the execpline where it was waiting that it was in a pipeline 346 * with a shell construct at the end (which may also be a shell function or 347 * several other things). When zsh sees the suspended grep, it forks to let 348 * the sub-shell execute the rest of the while loop. The parent shell walks 349 * up in the function call stack to the first execpline. There it has to find 350 * out that it has just forked and then has to add information about the sub- 351 * shell (its pid and the text for it) in the job entry of the cat. The pid 352 * is passed down in the list_pipe_pid variable. 353 * But there is a problem: the suspended grep is a child of the parent shell 354 * and can't be adopted by the sub-shell. So the parent shell also has to 355 * keep the information about this process (more precisely: this pipeline) 356 * by keeping the job table entry it created for it. The fact that there 357 * are two jobs which have to be treated together is remembered by setting 358 * the STAT_SUPERJOB flag in the entry for the cat-job (which now also 359 * contains a process-entry for the whole loop -- the sub-shell) and by 360 * setting STAT_SUBJOB in the job of the grep-job. With that we can keep 361 * sub-jobs from being displayed and we can handle an fg/bg on the super- 362 * job correctly. When the super-job is continued, the shell also wakes up 363 * the sub-job. But then, the grep will exit sometime. Now the parent shell 364 * has to remember not to try to wake it up again (in case of another ^Z). 365 * It also has to wake up the sub-shell (which suspended itself immediately 366 * after creation), so that the rest of the loop is executed by it. 367 * But there is more: when the sub-shell is created, the cat may already 368 * have exited, so we can't put the sub-shell in the process group of it. 369 * In this case, we put the sub-shell in the process group of the parent 370 * shell and in any case, the sub-shell has to put all commands executed 371 * by it into its own process group, because only this way the parent 372 * shell can control them since it only knows the process group of the sub- 373 * shell. Of course, this information is also important when putting a job 374 * in the foreground, where we have to attach its process group to the 375 * controlling tty. 376 * All this is made more difficult because we have to handle return values 377 * correctly. If the grep is signaled, its exit status has to be propagated 378 * back to the parent shell which needs it to set the exit status of the 379 * super-job. And of course, when the grep is signaled (including ^C), the 380 * loop has to be stopped, etc. 381 * The code for all this is distributed over three files (exec.c, jobs.c, 382 * and signals.c) and none of them is a simple one. So, all in all, there 383 * may still be bugs, but considering the complexity (with race conditions, 384 * signal handling, and all that), this should probably be expected. 385 */ 386 387/**/ 388int list_pipe = 0, simple_pline = 0; 389 390static pid_t list_pipe_pid; 391static struct timeval list_pipe_start; 392static int nowait, pline_level = 0; 393static int list_pipe_child = 0, list_pipe_job; 394static char list_pipe_text[JOBTEXTSIZE]; 395 396/* execute a current shell command */ 397 398/**/ 399static int 400execcursh(Estate state, int do_exec) 401{ 402 Wordcode end = state->pc + WC_CURSH_SKIP(state->pc[-1]); 403 404 /* Skip word only used for try/always */ 405 state->pc++; 406 407 /* 408 * The test thisjob != -1 was added because sometimes thisjob 409 * can be invalid at this point. The case in question was 410 * in a precmd function after operations involving background 411 * jobs. 412 * 413 * This is because sometimes we bypass job control to execute 414 * very simple functions via execssimple(). 415 */ 416 if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job && 417 !hasprocs(thisjob)) 418 deletejob(jobtab + thisjob, 0); 419 cmdpush(CS_CURSH); 420 execlist(state, 1, do_exec); 421 cmdpop(); 422 423 state->pc = end; 424 425 return lastval; 426} 427 428/* execve after handling $_ and #! */ 429 430#define POUNDBANGLIMIT 64 431 432/**/ 433static int 434zexecve(char *pth, char **argv, char **newenvp) 435{ 436 int eno; 437 static char buf[PATH_MAX * 2]; 438 char **eep; 439 440 unmetafy(pth, NULL); 441 for (eep = argv; *eep; eep++) 442 if (*eep != pth) 443 unmetafy(*eep, NULL); 444 buf[0] = '_'; 445 buf[1] = '='; 446 if (*pth == '/') 447 strcpy(buf + 2, pth); 448 else 449 sprintf(buf + 2, "%s/%s", pwd, pth); 450 zputenv(buf); 451#ifndef FD_CLOEXEC 452 closedumps(); 453#endif 454 455 if (newenvp == NULL) 456 newenvp = environ; 457 winch_unblock(); 458 execve(pth, argv, newenvp); 459 460 /* If the execve returns (which in general shouldn't happen), * 461 * then check for an errno equal to ENOEXEC. This errno is set * 462 * if the process file has the appropriate access permission, * 463 * but has an invalid magic number in its header. */ 464 if ((eno = errno) == ENOEXEC || eno == ENOENT) { 465 char execvebuf[POUNDBANGLIMIT + 1], *ptr, *ptr2, *argv0; 466 int fd, ct, t0; 467 468 if ((fd = open(pth, O_RDONLY|O_NOCTTY)) >= 0) { 469 argv0 = *argv; 470 *argv = pth; 471 ct = read(fd, execvebuf, POUNDBANGLIMIT); 472 close(fd); 473 if (ct > 0) { 474 if (execvebuf[0] == '#') { 475 if (execvebuf[1] == '!') { 476 for (t0 = 0; t0 != ct; t0++) 477 if (execvebuf[t0] == '\n') 478 break; 479 while (inblank(execvebuf[t0])) 480 execvebuf[t0--] = '\0'; 481 execvebuf[POUNDBANGLIMIT] = '\0'; 482 for (ptr = execvebuf + 2; *ptr && *ptr == ' '; ptr++); 483 for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++); 484 if (eno == ENOENT) { 485 char *pprog; 486 if (*ptr) 487 *ptr = '\0'; 488 if (*ptr2 != '/' && 489 (pprog = pathprog(ptr2, NULL))) { 490 argv[-2] = ptr2; 491 argv[-1] = ptr + 1; 492 winch_unblock(); 493 execve(pprog, argv - 2, newenvp); 494 } 495 zerr("%s: bad interpreter: %s: %e", pth, ptr2, 496 eno); 497 } else if (*ptr) { 498 *ptr = '\0'; 499 argv[-2] = ptr2; 500 argv[-1] = ptr + 1; 501 winch_unblock(); 502 execve(ptr2, argv - 2, newenvp); 503 } else { 504 argv[-1] = ptr2; 505 winch_unblock(); 506 execve(ptr2, argv - 1, newenvp); 507 } 508 } else if (eno == ENOEXEC) { 509 argv[-1] = "sh"; 510 winch_unblock(); 511 execve("/bin/sh", argv - 1, newenvp); 512 } 513 } else if (eno == ENOEXEC) { 514 for (t0 = 0; t0 != ct; t0++) 515 if (!execvebuf[t0]) 516 break; 517 if (t0 == ct) { 518 argv[-1] = "sh"; 519 winch_unblock(); 520 execve("/bin/sh", argv - 1, newenvp); 521 } 522 } 523 } else 524 eno = errno; 525 *argv = argv0; 526 } else 527 eno = errno; 528 } 529 /* restore the original arguments and path but do not bother with * 530 * null characters as these cannot be passed to external commands * 531 * anyway. So the result is truncated at the first null char. */ 532 pth = metafy(pth, -1, META_NOALLOC); 533 for (eep = argv; *eep; eep++) 534 if (*eep != pth) 535 (void) metafy(*eep, -1, META_NOALLOC); 536 return eno; 537} 538 539#define MAXCMDLEN (PATH_MAX*4) 540 541/* test whether we really want to believe the error number */ 542 543/**/ 544static int 545isgooderr(int e, char *dir) 546{ 547 /* 548 * Maybe the directory was unreadable, or maybe it wasn't 549 * even a directory. 550 */ 551 return ((e != EACCES || !access(dir, X_OK)) && 552 e != ENOENT && e != ENOTDIR); 553} 554 555/* 556 * Attempt to handle command not found. 557 * Return 0 if the condition was handled, non-zero otherwise. 558 */ 559 560/**/ 561static int 562commandnotfound(char *arg0, LinkList args) 563{ 564 Shfunc shf = (Shfunc) 565 shfunctab->getnode(shfunctab, "command_not_found_handler"); 566 567 if (!shf) 568 return 127; 569 570 pushnode(args, arg0); 571 return doshfunc(shf, args, 1); 572} 573 574/* execute an external command */ 575 576/**/ 577static void 578execute(LinkList args, int flags, int defpath) 579{ 580 Cmdnam cn; 581 char buf[MAXCMDLEN], buf2[MAXCMDLEN]; 582 char *s, *z, *arg0; 583 char **argv, **pp, **newenvp = NULL; 584 int eno = 0, ee; 585 586 arg0 = (char *) peekfirst(args); 587 if (isset(RESTRICTED) && (strchr(arg0, '/') || defpath)) { 588 zerr("%s: restricted", arg0); 589 _exit(1); 590 } 591 592 /* If the parameter STTY is set in the command's environment, * 593 * we first run the stty command with the value of this * 594 * parameter as it arguments. */ 595 if ((s = STTYval) && isatty(0) && (GETPGRP() == getpid())) { 596 char *t = tricat("stty", " ", s); 597 598 STTYval = 0; /* this prevents infinite recursion */ 599 zsfree(s); 600 execstring(t, 1, 0, "stty"); 601 zsfree(t); 602 } else if (s) { 603 STTYval = 0; 604 zsfree(s); 605 } 606 607 /* If ARGV0 is in the commands environment, we use * 608 * that as argv[0] for this external command */ 609 if (unset(RESTRICTED) && (z = zgetenv("ARGV0"))) { 610 setdata(firstnode(args), (void *) ztrdup(z)); 611 /* 612 * Note we don't do anything with the parameter structure 613 * for ARGV0: that's OK since we're about to exec or exit 614 * on failure. 615 */ 616#ifdef USE_SET_UNSET_ENV 617 unsetenv("ARGV0"); 618#else 619 delenvvalue(z - 6); 620#endif 621 } else if (flags & BINF_DASH) { 622 /* Else if the pre-command `-' was given, we add `-' * 623 * to the front of argv[0] for this command. */ 624 sprintf(buf2, "-%s", arg0); 625 setdata(firstnode(args), (void *) ztrdup(buf2)); 626 } 627 628 argv = makecline(args); 629 if (flags & BINF_CLEARENV) 630 newenvp = blank_env; 631 632 /* 633 * Note that we don't close fd's attached to process substitution 634 * here, which should be visible to external processes. 635 */ 636 closem(FDT_XTRACE); 637#ifndef FD_CLOEXEC 638 if (SHTTY != -1) { 639 close(SHTTY); 640 SHTTY = -1; 641 } 642#endif 643 child_unblock(); 644 if ((int) strlen(arg0) >= PATH_MAX) { 645 zerr("command too long: %s", arg0); 646 _exit(1); 647 } 648 for (s = arg0; *s; s++) 649 if (*s == '/') { 650 int lerrno = zexecve(arg0, argv, newenvp); 651 if (arg0 == s || unset(PATHDIRS) || 652 (arg0[0] == '.' && (arg0 + 1 == s || 653 (arg0[1] == '.' && arg0 + 2 == s)))) { 654 zerr("%e: %s", lerrno, arg0); 655 _exit((lerrno == EACCES || lerrno == ENOEXEC) ? 126 : 127); 656 } 657 break; 658 } 659 660 /* for command -p, search the default path */ 661 if (defpath) { 662 char *s, pbuf[PATH_MAX]; 663 char *dptr, *pe, *ps = DEFAULT_PATH; 664 665 for(;ps;ps = pe ? pe+1 : NULL) { 666 pe = strchr(ps, ':'); 667 if (*ps == '/') { 668 s = pbuf; 669 if (pe) 670 struncpy(&s, ps, pe-ps); 671 else 672 strucpy(&s, ps); 673 *s++ = '/'; 674 if ((s - pbuf) + strlen(arg0) >= PATH_MAX) 675 continue; 676 strucpy(&s, arg0); 677 if (iscom(pbuf)) 678 break; 679 } 680 } 681 682 if (!ps) { 683 if (commandnotfound(arg0, args) == 0) 684 _exit(0); 685 zerr("command not found: %s", arg0); 686 _exit(127); 687 } 688 689 ee = zexecve(pbuf, argv, newenvp); 690 691 if ((dptr = strrchr(pbuf, '/'))) 692 *dptr = '\0'; 693 if (isgooderr(ee, *pbuf ? pbuf : "/")) 694 eno = ee; 695 696 } else { 697 698 if ((cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0))) { 699 char nn[PATH_MAX], *dptr; 700 701 if (cn->node.flags & HASHED) 702 strcpy(nn, cn->u.cmd); 703 else { 704 for (pp = path; pp < cn->u.name; pp++) 705 if (!**pp || (**pp == '.' && (*pp)[1] == '\0')) { 706 ee = zexecve(arg0, argv, newenvp); 707 if (isgooderr(ee, *pp)) 708 eno = ee; 709 } else if (**pp != '/') { 710 z = buf; 711 strucpy(&z, *pp); 712 *z++ = '/'; 713 strcpy(z, arg0); 714 ee = zexecve(buf, argv, newenvp); 715 if (isgooderr(ee, *pp)) 716 eno = ee; 717 } 718 strcpy(nn, cn->u.name ? *(cn->u.name) : ""); 719 strcat(nn, "/"); 720 strcat(nn, cn->node.nam); 721 } 722 ee = zexecve(nn, argv, newenvp); 723 724 if ((dptr = strrchr(nn, '/'))) 725 *dptr = '\0'; 726 if (isgooderr(ee, *nn ? nn : "/")) 727 eno = ee; 728 } 729 for (pp = path; *pp; pp++) 730 if (!(*pp)[0] || ((*pp)[0] == '.' && !(*pp)[1])) { 731 ee = zexecve(arg0, argv, newenvp); 732 if (isgooderr(ee, *pp)) 733 eno = ee; 734 } else { 735 z = buf; 736 strucpy(&z, *pp); 737 *z++ = '/'; 738 strcpy(z, arg0); 739 ee = zexecve(buf, argv, newenvp); 740 if (isgooderr(ee, *pp)) 741 eno = ee; 742 } 743 } 744 745 if (eno) 746 zerr("%e: %s", eno, arg0); 747 else if (commandnotfound(arg0, args) == 0) 748 _exit(0); 749 else 750 zerr("command not found: %s", arg0); 751 _exit((eno == EACCES || eno == ENOEXEC) ? 126 : 127); 752} 753 754#define RET_IF_COM(X) { if (iscom(X)) return docopy ? dupstring(X) : arg0; } 755 756/* 757 * Get the full pathname of an external command. 758 * If the second argument is zero, return the first argument if found; 759 * if non-zero, return the path using heap memory. (RET_IF_COM(X), above). 760 */ 761 762/**/ 763mod_export char * 764findcmd(char *arg0, int docopy) 765{ 766 char **pp; 767 char *z, *s, buf[MAXCMDLEN]; 768 Cmdnam cn; 769 770 cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0); 771 if (!cn && isset(HASHCMDS)) 772 cn = hashcmd(arg0, path); 773 if ((int) strlen(arg0) > PATH_MAX) 774 return NULL; 775 for (s = arg0; *s; s++) 776 if (*s == '/') { 777 RET_IF_COM(arg0); 778 if (arg0 == s || unset(PATHDIRS)) { 779 return NULL; 780 } 781 break; 782 } 783 if (cn) { 784 char nn[PATH_MAX]; 785 786 if (cn->node.flags & HASHED) 787 strcpy(nn, cn->u.cmd); 788 else { 789 for (pp = path; pp < cn->u.name; pp++) 790 if (**pp != '/') { 791 z = buf; 792 if (**pp) { 793 strucpy(&z, *pp); 794 *z++ = '/'; 795 } 796 strcpy(z, arg0); 797 RET_IF_COM(buf); 798 } 799 strcpy(nn, cn->u.name ? *(cn->u.name) : ""); 800 strcat(nn, "/"); 801 strcat(nn, cn->node.nam); 802 } 803 RET_IF_COM(nn); 804 } 805 for (pp = path; *pp; pp++) { 806 z = buf; 807 if (**pp) { 808 strucpy(&z, *pp); 809 *z++ = '/'; 810 } 811 strcpy(z, arg0); 812 RET_IF_COM(buf); 813 } 814 return NULL; 815} 816 817/**/ 818int 819iscom(char *s) 820{ 821 struct stat statbuf; 822 char *us = unmeta(s); 823 824 return (access(us, X_OK) == 0 && stat(us, &statbuf) >= 0 && 825 S_ISREG(statbuf.st_mode)); 826} 827 828/**/ 829int 830isreallycom(Cmdnam cn) 831{ 832 char fullnam[MAXCMDLEN]; 833 834 if (cn->node.flags & HASHED) 835 strcpy(fullnam, cn->u.cmd); 836 else if (!cn->u.name) 837 return 0; 838 else { 839 strcpy(fullnam, *(cn->u.name)); 840 strcat(fullnam, "/"); 841 strcat(fullnam, cn->node.nam); 842 } 843 return iscom(fullnam); 844} 845 846/**/ 847int 848isrelative(char *s) 849{ 850 if (*s != '/') 851 return 1; 852 for (; *s; s++) 853 if (*s == '.' && s[-1] == '/' && 854 (s[1] == '/' || s[1] == '\0' || 855 (s[1] == '.' && (s[2] == '/' || s[2] == '\0')))) 856 return 1; 857 return 0; 858} 859 860/**/ 861mod_export Cmdnam 862hashcmd(char *arg0, char **pp) 863{ 864 Cmdnam cn; 865 char *s, buf[PATH_MAX]; 866 char **pq; 867 868 for (; *pp; pp++) 869 if (**pp == '/') { 870 s = buf; 871 strucpy(&s, *pp); 872 *s++ = '/'; 873 if ((s - buf) + strlen(arg0) >= PATH_MAX) 874 continue; 875 strcpy(s, arg0); 876 if (iscom(buf)) 877 break; 878 } 879 880 if (!*pp) 881 return NULL; 882 883 cn = (Cmdnam) zshcalloc(sizeof *cn); 884 cn->node.flags = 0; 885 cn->u.name = pp; 886 cmdnamtab->addnode(cmdnamtab, ztrdup(arg0), cn); 887 888 if (isset(HASHDIRS)) { 889 for (pq = pathchecked; pq <= pp; pq++) 890 hashdir(pq); 891 pathchecked = pp + 1; 892 } 893 894 return cn; 895} 896 897/**/ 898int 899forklevel; 900 901/* Arguments to entersubsh() */ 902enum { 903 /* Subshell is to be run asynchronously (else synchronously) */ 904 ESUB_ASYNC = 0x01, 905 /* 906 * Perform process group and tty handling and clear the 907 * (real) job table, since it won't be any longer valid 908 */ 909 ESUB_PGRP = 0x02, 910 /* Don't unset traps */ 911 ESUB_KEEPTRAP = 0x04, 912 /* This is only a fake entry to a subshell */ 913 ESUB_FAKE = 0x08, 914 /* Release the process group if pid is the shell's process group */ 915 ESUB_REVERTPGRP = 0x10, 916 /* Don't handle the MONITOR option even if previously set */ 917 ESUB_NOMONITOR = 0x20, 918 /* This is a subshell where job control is allowed */ 919 ESUB_JOB_CONTROL = 0x40 920}; 921 922/**/ 923static void 924entersubsh(int flags) 925{ 926 int sig, monitor, job_control_ok; 927 928 if (!(flags & ESUB_KEEPTRAP)) 929 for (sig = 0; sig < VSIGCOUNT; sig++) 930 if (!(sigtrapped[sig] & ZSIG_FUNC) && 931 sig != SIGDEBUG && sig != SIGZERR) 932 unsettrap(sig); 933 monitor = isset(MONITOR); 934 job_control_ok = monitor && (flags & ESUB_JOB_CONTROL) && isset(POSIXJOBS); 935 if (flags & ESUB_NOMONITOR) 936 opts[MONITOR] = 0; 937 if (!isset(MONITOR)) { 938 if (flags & ESUB_ASYNC) { 939 settrap(SIGINT, NULL, 0); 940 settrap(SIGQUIT, NULL, 0); 941 if (isatty(0)) { 942 close(0); 943 if (open("/dev/null", O_RDWR | O_NOCTTY)) { 944 zerr("can't open /dev/null: %e", errno); 945 _exit(1); 946 } 947 } 948 } 949 } else if (thisjob != -1 && (flags & ESUB_PGRP)) { 950 if (jobtab[list_pipe_job].gleader && (list_pipe || list_pipe_child)) { 951 if (setpgrp(0L, jobtab[list_pipe_job].gleader) == -1 || 952 killpg(jobtab[list_pipe_job].gleader, 0) == -1) { 953 jobtab[list_pipe_job].gleader = 954 jobtab[thisjob].gleader = (list_pipe_child ? mypgrp : getpid()); 955 setpgrp(0L, jobtab[list_pipe_job].gleader); 956 if (!(flags & ESUB_ASYNC)) 957 attachtty(jobtab[thisjob].gleader); 958 } 959 } 960 else if (!jobtab[thisjob].gleader || 961 setpgrp(0L, jobtab[thisjob].gleader) == -1) { 962 /* 963 * This is the standard point at which a newly started 964 * process gets put into the foreground by taking over 965 * the terminal. Note that in normal circumstances we do 966 * this only from the process itself. This only works if 967 * we are still ignoring SIGTTOU at this point; in this 968 * case ignoring the signal has the special effect that 969 * the operation is allowed to work (in addition to not 970 * causing the shell to be suspended). 971 */ 972 jobtab[thisjob].gleader = getpid(); 973 if (list_pipe_job != thisjob && 974 !jobtab[list_pipe_job].gleader) 975 jobtab[list_pipe_job].gleader = jobtab[thisjob].gleader; 976 setpgrp(0L, jobtab[thisjob].gleader); 977 if (!(flags & ESUB_ASYNC)) 978 attachtty(jobtab[thisjob].gleader); 979 } 980 } 981 if (!(flags & ESUB_FAKE)) 982 subsh = 1; 983 /* 984 * Increment the visible parameter ZSH_SUBSHELL even if this 985 * is a fake subshell because we are exec'ing at the end. 986 * Logically this should be equivalent to a real subshell so 987 * we don't hang out the dirty washing. 988 */ 989 zsh_subshell++; 990 if ((flags & ESUB_REVERTPGRP) && getpid() == mypgrp) 991 release_pgrp(); 992 shout = NULL; 993 if (!job_control_ok) { 994 /* 995 * If this process is not goign to be doing job control, 996 * we don't want to do special things with the corresponding 997 * signals. If it is, we need to keep the special behaviour: 998 * see note about attachtty() above. 999 */ 1000 signal_default(SIGTTOU); 1001 signal_default(SIGTTIN); 1002 signal_default(SIGTSTP); 1003 } 1004 if (interact) { 1005 signal_default(SIGTERM); 1006 if (!(sigtrapped[SIGINT] & ZSIG_IGNORED)) 1007 signal_default(SIGINT); 1008 } 1009 if (!(sigtrapped[SIGQUIT] & ZSIG_IGNORED)) 1010 signal_default(SIGQUIT); 1011 if (!job_control_ok) 1012 opts[MONITOR] = 0; 1013 opts[USEZLE] = 0; 1014 zleactive = 0; 1015 if (flags & ESUB_PGRP) 1016 clearjobtab(monitor); 1017 get_usage(); 1018 forklevel = locallevel; 1019} 1020 1021/* execute a string */ 1022 1023/**/ 1024mod_export void 1025execstring(char *s, int dont_change_job, int exiting, char *context) 1026{ 1027 Eprog prog; 1028 1029 pushheap(); 1030 if (isset(VERBOSE)) { 1031 zputs(s, stderr); 1032 fputc('\n', stderr); 1033 fflush(stderr); 1034 } 1035 if ((prog = parse_string(s, 0))) 1036 execode(prog, dont_change_job, exiting, context); 1037 popheap(); 1038} 1039 1040/**/ 1041mod_export void 1042execode(Eprog p, int dont_change_job, int exiting, char *context) 1043{ 1044 struct estate s; 1045 static int zsh_eval_context_len; 1046 int alen; 1047 1048 if (!zsh_eval_context_len) { 1049 zsh_eval_context_len = 16; 1050 alen = 0; 1051 zsh_eval_context = (char **)zalloc(zsh_eval_context_len * 1052 sizeof(*zsh_eval_context)); 1053 } else { 1054 alen = arrlen(zsh_eval_context); 1055 if (zsh_eval_context_len == alen + 1) { 1056 zsh_eval_context_len *= 2; 1057 zsh_eval_context = zrealloc(zsh_eval_context, 1058 zsh_eval_context_len * 1059 sizeof(*zsh_eval_context)); 1060 } 1061 } 1062 zsh_eval_context[alen] = context; 1063 zsh_eval_context[alen+1] = NULL; 1064 1065 s.prog = p; 1066 s.pc = p->prog; 1067 s.strs = p->strs; 1068 useeprog(p); /* Mark as in use */ 1069 1070 execlist(&s, dont_change_job, exiting); 1071 1072 freeeprog(p); /* Free if now unused */ 1073 1074 /* 1075 * zsh_eval_context may have been altered by a recursive 1076 * call, but that's OK since we're using the global value. 1077 */ 1078 zsh_eval_context[alen] = NULL; 1079} 1080 1081/* Execute a simplified command. This is used to execute things that 1082 * will run completely in the shell, so that we can by-pass all that 1083 * nasty job-handling and redirection stuff in execpline and execcmd. */ 1084 1085/**/ 1086static int 1087execsimple(Estate state) 1088{ 1089 wordcode code = *state->pc++; 1090 int lv, otj; 1091 1092 if (errflag) 1093 return (lastval = 1); 1094 1095 if (!isset(EXECOPT)) 1096 return lastval = 0; 1097 1098 /* In evaluated traps, don't modify the line number. */ 1099 if (!IN_EVAL_TRAP() && !ineval && code) 1100 lineno = code - 1; 1101 1102 code = wc_code(*state->pc++); 1103 1104 /* 1105 * Because we're bypassing job control, ensure the called 1106 * code doesn't see the current job. 1107 */ 1108 otj = thisjob; 1109 thisjob = -1; 1110 1111 if (code == WC_ASSIGN) { 1112 cmdoutval = 0; 1113 addvars(state, state->pc - 1, 0); 1114 if (isset(XTRACE)) { 1115 fputc('\n', xtrerr); 1116 fflush(xtrerr); 1117 } 1118 lv = (errflag ? errflag : cmdoutval); 1119 } else 1120 lv = (execfuncs[code - WC_CURSH])(state, 0); 1121 1122 thisjob = otj; 1123 1124 return lastval = lv; 1125} 1126 1127/* Main routine for executing a list. * 1128 * exiting means that the (sub)shell we are in is a definite goner * 1129 * after the current list is finished, so we may be able to exec the * 1130 * last command directly instead of forking. If dont_change_job is * 1131 * nonzero, then restore the current job number after executing the * 1132 * list. */ 1133 1134/**/ 1135void 1136execlist(Estate state, int dont_change_job, int exiting) 1137{ 1138 static int donetrap; 1139 Wordcode next; 1140 wordcode code; 1141 int ret, cj, csp, ltype; 1142 int old_pline_level, old_list_pipe; 1143 zlong oldlineno; 1144 /* 1145 * ERREXIT only forces the shell to exit if the last command in a && 1146 * or || fails. This is the case even if an earlier command is a 1147 * shell function or other current shell structure, so we have to set 1148 * noerrexit here if the sublist is not of type END. 1149 */ 1150 int oldnoerrexit = noerrexit; 1151 1152 cj = thisjob; 1153 old_pline_level = pline_level; 1154 old_list_pipe = list_pipe; 1155 oldlineno = lineno; 1156 1157 if (sourcelevel && unset(SHINSTDIN)) 1158 pline_level = list_pipe = 0; 1159 1160 /* Loop over all sets of comands separated by newline, * 1161 * semi-colon or ampersand (`sublists'). */ 1162 code = *state->pc++; 1163 if (wc_code(code) != WC_LIST) { 1164 /* Empty list; this returns status zero. */ 1165 lastval = 0; 1166 } 1167 while (wc_code(code) == WC_LIST && !breaks && !retflag && !errflag) { 1168 int donedebug; 1169 1170 ltype = WC_LIST_TYPE(code); 1171 csp = cmdsp; 1172 1173 if (!IN_EVAL_TRAP() && !ineval) { 1174 /* 1175 * Ensure we have a valid line number for debugging, 1176 * unless we are in an evaluated trap in which case 1177 * we retain the line number from the context. 1178 * This was added for DEBUGBEFORECMD but I've made 1179 * it unconditional to keep dependencies to a minimum. 1180 * 1181 * The line number is updated for individual pipelines. 1182 * This isn't necessary for debug traps since they only 1183 * run once per sublist. 1184 */ 1185 wordcode code2 = *state->pc, lnp1 = 0; 1186 if (ltype & Z_SIMPLE) { 1187 lnp1 = code2; 1188 } else if (wc_code(code2) == WC_SUBLIST) { 1189 if (WC_SUBLIST_FLAGS(code2) == WC_SUBLIST_SIMPLE) 1190 lnp1 = state->pc[1]; 1191 else 1192 lnp1 = WC_PIPE_LINENO(state->pc[1]); 1193 } 1194 if (lnp1) 1195 lineno = lnp1 - 1; 1196 } 1197 1198 if (sigtrapped[SIGDEBUG] && isset(DEBUGBEFORECMD) && !intrap) { 1199 Wordcode pc2 = state->pc; 1200 int oerrexit_opt = opts[ERREXIT]; 1201 Param pm; 1202 opts[ERREXIT] = 0; 1203 noerrexit = 1; 1204 if (ltype & Z_SIMPLE) /* skip the line number */ 1205 pc2++; 1206 pm = setsparam("ZSH_DEBUG_CMD", getpermtext(state->prog, pc2, 0)); 1207 1208 exiting = donetrap; 1209 ret = lastval; 1210 dotrap(SIGDEBUG); 1211 if (!retflag) 1212 lastval = ret; 1213 donetrap = exiting; 1214 noerrexit = oldnoerrexit; 1215 /* 1216 * Only execute the trap once per sublist, even 1217 * if the DEBUGBEFORECMD option changes. 1218 */ 1219 donedebug = isset(ERREXIT) ? 2 : 1; 1220 opts[ERREXIT] = oerrexit_opt; 1221 if (pm) 1222 unsetparam_pm(pm, 0, 1); 1223 } else 1224 donedebug = intrap ? 1 : 0; 1225 1226 /* Reset donetrap: this ensures that a trap is only * 1227 * called once for each sublist that fails. */ 1228 donetrap = 0; 1229 if (ltype & Z_SIMPLE) { 1230 next = state->pc + WC_LIST_SKIP(code); 1231 if (donedebug != 2) 1232 execsimple(state); 1233 state->pc = next; 1234 goto sublist_done; 1235 } 1236 1237 /* Loop through code followed by &&, ||, or end of sublist. */ 1238 code = *state->pc++; 1239 if (donedebug == 2) { 1240 /* Skip sublist. */ 1241 while (wc_code(code) == WC_SUBLIST) { 1242 state->pc = state->pc + WC_SUBLIST_SKIP(code); 1243 if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) 1244 break; 1245 code = *state->pc++; 1246 } 1247 donetrap = 1; 1248 /* yucky but consistent... */ 1249 goto sublist_done; 1250 } 1251 while (wc_code(code) == WC_SUBLIST) { 1252 next = state->pc + WC_SUBLIST_SKIP(code); 1253 if (!oldnoerrexit) 1254 noerrexit = (WC_SUBLIST_TYPE(code) != WC_SUBLIST_END); 1255 switch (WC_SUBLIST_TYPE(code)) { 1256 case WC_SUBLIST_END: 1257 /* End of sublist; just execute, ignoring status. */ 1258 if (WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) 1259 execsimple(state); 1260 else 1261 execpline(state, code, ltype, (ltype & Z_END) && exiting); 1262 state->pc = next; 1263 goto sublist_done; 1264 break; 1265 case WC_SUBLIST_AND: 1266 /* If the return code is non-zero, we skip pipelines until * 1267 * we find a sublist followed by ORNEXT. */ 1268 if ((ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ? 1269 execsimple(state) : 1270 execpline(state, code, Z_SYNC, 0)))) { 1271 state->pc = next; 1272 code = *state->pc++; 1273 next = state->pc + WC_SUBLIST_SKIP(code); 1274 while (wc_code(code) == WC_SUBLIST && 1275 WC_SUBLIST_TYPE(code) == WC_SUBLIST_AND) { 1276 state->pc = next; 1277 code = *state->pc++; 1278 next = state->pc + WC_SUBLIST_SKIP(code); 1279 } 1280 if (wc_code(code) != WC_SUBLIST) { 1281 /* We've skipped to the end of the list, not executing * 1282 * the final pipeline, so don't perform error handling * 1283 * for this sublist. */ 1284 donetrap = 1; 1285 goto sublist_done; 1286 } else if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) { 1287 donetrap = 1; 1288 /* 1289 * Treat this in the same way as if we reached 1290 * the end of the sublist normally. 1291 */ 1292 state->pc = next; 1293 goto sublist_done; 1294 } 1295 } 1296 cmdpush(CS_CMDAND); 1297 break; 1298 case WC_SUBLIST_OR: 1299 /* If the return code is zero, we skip pipelines until * 1300 * we find a sublist followed by ANDNEXT. */ 1301 if (!(ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ? 1302 execsimple(state) : 1303 execpline(state, code, Z_SYNC, 0)))) { 1304 state->pc = next; 1305 code = *state->pc++; 1306 next = state->pc + WC_SUBLIST_SKIP(code); 1307 while (wc_code(code) == WC_SUBLIST && 1308 WC_SUBLIST_TYPE(code) == WC_SUBLIST_OR) { 1309 state->pc = next; 1310 code = *state->pc++; 1311 next = state->pc + WC_SUBLIST_SKIP(code); 1312 } 1313 if (wc_code(code) != WC_SUBLIST) { 1314 /* We've skipped to the end of the list, not executing * 1315 * the final pipeline, so don't perform error handling * 1316 * for this sublist. */ 1317 donetrap = 1; 1318 goto sublist_done; 1319 } else if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) { 1320 donetrap = 1; 1321 /* 1322 * Treat this in the same way as if we reached 1323 * the end of the sublist normally. 1324 */ 1325 state->pc = next; 1326 goto sublist_done; 1327 } 1328 } 1329 cmdpush(CS_CMDOR); 1330 break; 1331 } 1332 state->pc = next; 1333 code = *state->pc++; 1334 } 1335 state->pc--; 1336sublist_done: 1337 1338 noerrexit = oldnoerrexit; 1339 1340 if (sigtrapped[SIGDEBUG] && !isset(DEBUGBEFORECMD) && !donedebug) { 1341 /* 1342 * Save and restore ERREXIT for consistency with 1343 * DEBUGBEFORECMD, even though it's not used. 1344 */ 1345 int oerrexit_opt = opts[ERREXIT]; 1346 opts[ERREXIT] = 0; 1347 noerrexit = 1; 1348 exiting = donetrap; 1349 ret = lastval; 1350 dotrap(SIGDEBUG); 1351 if (!retflag) 1352 lastval = ret; 1353 donetrap = exiting; 1354 noerrexit = oldnoerrexit; 1355 opts[ERREXIT] = oerrexit_opt; 1356 } 1357 1358 cmdsp = csp; 1359 1360 /* Check whether we are suppressing traps/errexit * 1361 * (typically in init scripts) and if we haven't * 1362 * already performed them for this sublist. */ 1363 if (!noerrexit && !donetrap) { 1364 if (sigtrapped[SIGZERR] && lastval) { 1365 dotrap(SIGZERR); 1366 donetrap = 1; 1367 } 1368 if (lastval) { 1369 int errreturn = isset(ERRRETURN) && 1370 (isset(INTERACTIVE) || locallevel || sourcelevel); 1371 int errexit = isset(ERREXIT) || 1372 (isset(ERRRETURN) && !errreturn); 1373 if (errexit) { 1374 if (sigtrapped[SIGEXIT]) 1375 dotrap(SIGEXIT); 1376 if (mypid != getpid()) 1377 _exit(lastval); 1378 else 1379 exit(lastval); 1380 } 1381 if (errreturn) { 1382 retflag = 1; 1383 breaks = loops; 1384 } 1385 } 1386 } 1387 if (ltype & Z_END) 1388 break; 1389 code = *state->pc++; 1390 } 1391 pline_level = old_pline_level; 1392 list_pipe = old_list_pipe; 1393 lineno = oldlineno; 1394 if (dont_change_job) 1395 thisjob = cj; 1396 1397 if (exiting && sigtrapped[SIGEXIT]) { 1398 dotrap(SIGEXIT); 1399 /* Make sure this doesn't get executed again. */ 1400 sigtrapped[SIGEXIT] = 0; 1401 } 1402} 1403 1404/* Execute a pipeline. * 1405 * last1 is a flag that this command is the last command in a shell * 1406 * that is about to exit, so we can exec instead of forking. It gets * 1407 * passed all the way down to execcmd() which actually makes the * 1408 * decision. A 0 is always passed if the command is not the last in * 1409 * the pipeline. This function assumes that the sublist is not NULL. * 1410 * If last1 is zero but the command is at the end of a pipeline, we * 1411 * pass 2 down to execcmd(). * 1412 */ 1413 1414/**/ 1415static int 1416execpline(Estate state, wordcode slcode, int how, int last1) 1417{ 1418 int ipipe[2], opipe[2]; 1419 int pj, newjob; 1420 int old_simple_pline = simple_pline; 1421 int slflags = WC_SUBLIST_FLAGS(slcode); 1422 wordcode code = *state->pc++; 1423 static int lastwj, lpforked; 1424 1425 if (wc_code(code) != WC_PIPE) 1426 return lastval = (slflags & WC_SUBLIST_NOT) != 0; 1427 else if (slflags & WC_SUBLIST_NOT) 1428 last1 = 0; 1429 1430 pj = thisjob; 1431 ipipe[0] = ipipe[1] = opipe[0] = opipe[1] = 0; 1432 child_block(); 1433 1434 /* 1435 * Get free entry in job table and initialize it. This is currently 1436 * the only call to initjob() (apart from a minor exception in 1437 * clearjobtab()), so this is also the only place where we can 1438 * expand the job table under us. 1439 */ 1440 if ((thisjob = newjob = initjob()) == -1) { 1441 child_unblock(); 1442 return 1; 1443 } 1444 if (how & Z_TIMED) 1445 jobtab[thisjob].stat |= STAT_TIMED; 1446 1447 if (slflags & WC_SUBLIST_COPROC) { 1448 how = Z_ASYNC; 1449 if (coprocin >= 0) { 1450 zclose(coprocin); 1451 zclose(coprocout); 1452 } 1453 if (mpipe(ipipe) < 0) { 1454 coprocin = coprocout = -1; 1455 slflags &= ~WC_SUBLIST_COPROC; 1456 } else if (mpipe(opipe) < 0) { 1457 close(ipipe[0]); 1458 close(ipipe[1]); 1459 coprocin = coprocout = -1; 1460 slflags &= ~WC_SUBLIST_COPROC; 1461 } else { 1462 coprocin = ipipe[0]; 1463 coprocout = opipe[1]; 1464 fdtable[coprocin] = fdtable[coprocout] = FDT_UNUSED; 1465 } 1466 } 1467 /* This used to set list_pipe_pid=0 unconditionally, but in things 1468 * like `ls|if true; then sleep 20; cat; fi' where the sleep was 1469 * stopped, the top-level execpline() didn't get the pid for the 1470 * sub-shell because it was overwritten. */ 1471 if (!pline_level++) { 1472 list_pipe_pid = 0; 1473 nowait = 0; 1474 simple_pline = (WC_PIPE_TYPE(code) == WC_PIPE_END); 1475 list_pipe_job = newjob; 1476 } 1477 lastwj = lpforked = 0; 1478 execpline2(state, code, how, opipe[0], ipipe[1], last1); 1479 pline_level--; 1480 if (how & Z_ASYNC) { 1481 lastwj = newjob; 1482 1483 if (thisjob == list_pipe_job) 1484 list_pipe_job = 0; 1485 jobtab[thisjob].stat |= STAT_NOSTTY; 1486 if (slflags & WC_SUBLIST_COPROC) { 1487 zclose(ipipe[1]); 1488 zclose(opipe[0]); 1489 } 1490 if (how & Z_DISOWN) { 1491 deletejob(jobtab + thisjob, 1); 1492 thisjob = -1; 1493 } 1494 else 1495 spawnjob(); 1496 child_unblock(); 1497 /* Executing background code resets shell status */ 1498 return lastval = 0; 1499 } else { 1500 if (newjob != lastwj) { 1501 Job jn = jobtab + newjob; 1502 int updated; 1503 1504 if (newjob == list_pipe_job && list_pipe_child) 1505 _exit(0); 1506 1507 lastwj = thisjob = newjob; 1508 1509 if (list_pipe || (pline_level && !(how & Z_TIMED))) 1510 jn->stat |= STAT_NOPRINT; 1511 1512 if (nowait) { 1513 if(!pline_level) { 1514 struct process *pn, *qn; 1515 1516 curjob = newjob; 1517 DPUTS(!list_pipe_pid, "invalid list_pipe_pid"); 1518 addproc(list_pipe_pid, list_pipe_text, 0, 1519 &list_pipe_start); 1520 1521 /* If the super-job contains only the sub-shell, the 1522 sub-shell is the group leader. */ 1523 if (!jn->procs->next || lpforked == 2) { 1524 jn->gleader = list_pipe_pid; 1525 jn->stat |= STAT_SUBLEADER; 1526 } 1527 for (pn = jobtab[jn->other].procs; pn; pn = pn->next) 1528 if (WIFSTOPPED(pn->status)) 1529 break; 1530 1531 if (pn) { 1532 for (qn = jn->procs; qn->next; qn = qn->next); 1533 qn->status = pn->status; 1534 } 1535 1536 jn->stat &= ~(STAT_DONE | STAT_NOPRINT); 1537 jn->stat |= STAT_STOPPED | STAT_CHANGED | STAT_LOCKED; 1538 printjob(jn, !!isset(LONGLISTJOBS), 1); 1539 } 1540 else if (newjob != list_pipe_job) 1541 deletejob(jn, 0); 1542 else 1543 lastwj = -1; 1544 } 1545 1546 errbrk_saved = 0; 1547 for (; !nowait;) { 1548 if (list_pipe_child) { 1549 jn->stat |= STAT_NOPRINT; 1550 makerunning(jn); 1551 } 1552 if (!(jn->stat & STAT_LOCKED)) { 1553 updated = hasprocs(thisjob); 1554 waitjobs(); 1555 child_block(); 1556 } else 1557 updated = 0; 1558 if (!updated && 1559 list_pipe_job && hasprocs(list_pipe_job) && 1560 !(jobtab[list_pipe_job].stat & STAT_STOPPED)) { 1561 child_unblock(); 1562 child_block(); 1563 } 1564 if (list_pipe_child && 1565 jn->stat & STAT_DONE && 1566 lastval2 & 0200) 1567 killpg(mypgrp, lastval2 & ~0200); 1568 if (!list_pipe_child && !lpforked && !subsh && jobbing && 1569 (list_pipe || last1 || pline_level) && 1570 ((jn->stat & STAT_STOPPED) || 1571 (list_pipe_job && pline_level && 1572 (jobtab[list_pipe_job].stat & STAT_STOPPED)))) { 1573 pid_t pid = 0; 1574 int synch[2]; 1575 struct timeval bgtime; 1576 1577 if (pipe(synch) < 0 || (pid = zfork(&bgtime)) == -1) { 1578 if (pid < 0) { 1579 close(synch[0]); 1580 close(synch[1]); 1581 } else 1582 zerr("pipe failed: %e", errno); 1583 zleentry(ZLE_CMD_TRASH); 1584 fprintf(stderr, "zsh: job can't be suspended\n"); 1585 fflush(stderr); 1586 makerunning(jn); 1587 killjb(jn, SIGCONT); 1588 thisjob = newjob; 1589 } 1590 else if (pid) { 1591 char dummy; 1592 1593 lpforked = 1594 (killpg(jobtab[list_pipe_job].gleader, 0) == -1 ? 2 : 1); 1595 list_pipe_pid = pid; 1596 list_pipe_start = bgtime; 1597 nowait = errflag = 1; 1598 breaks = loops; 1599 close(synch[1]); 1600 read_loop(synch[0], &dummy, 1); 1601 close(synch[0]); 1602 /* If this job has finished, we leave it as a 1603 * normal (non-super-) job. */ 1604 if (!(jn->stat & STAT_DONE)) { 1605 jobtab[list_pipe_job].other = newjob; 1606 jobtab[list_pipe_job].stat |= STAT_SUPERJOB; 1607 jn->stat |= STAT_SUBJOB | STAT_NOPRINT; 1608 jn->other = pid; 1609 } 1610 if ((list_pipe || last1) && hasprocs(list_pipe_job)) 1611 killpg(jobtab[list_pipe_job].gleader, SIGSTOP); 1612 break; 1613 } 1614 else { 1615 close(synch[0]); 1616 entersubsh(ESUB_ASYNC); 1617 if (jobtab[list_pipe_job].procs) { 1618 if (setpgrp(0L, mypgrp = jobtab[list_pipe_job].gleader) 1619 == -1) { 1620 setpgrp(0L, mypgrp = getpid()); 1621 } 1622 } else 1623 setpgrp(0L, mypgrp = getpid()); 1624 close(synch[1]); 1625 kill(getpid(), SIGSTOP); 1626 list_pipe = 0; 1627 list_pipe_child = 1; 1628 opts[INTERACTIVE] = 0; 1629 if (errbrk_saved) { 1630 errflag = prev_errflag; 1631 breaks = prev_breaks; 1632 } 1633 break; 1634 } 1635 } 1636 else if (subsh && jn->stat & STAT_STOPPED) 1637 thisjob = newjob; 1638 else 1639 break; 1640 } 1641 child_unblock(); 1642 1643 if (list_pipe && (lastval & 0200) && pj >= 0 && 1644 (!(jn->stat & STAT_INUSE) || (jn->stat & STAT_DONE))) { 1645 deletejob(jn, 0); 1646 jn = jobtab + pj; 1647 if (jn->gleader) 1648 killjb(jn, lastval & ~0200); 1649 } 1650 if (list_pipe_child || 1651 ((jn->stat & STAT_DONE) && 1652 (list_pipe || (pline_level && !(jn->stat & STAT_SUBJOB))))) 1653 deletejob(jn, 0); 1654 thisjob = pj; 1655 } 1656 if ((slflags & WC_SUBLIST_NOT) && !errflag) 1657 lastval = !lastval; 1658 } 1659 if (!pline_level) 1660 simple_pline = old_simple_pline; 1661 return lastval; 1662} 1663 1664/* execute pipeline. This function assumes the `pline' is not NULL. */ 1665 1666/**/ 1667static void 1668execpline2(Estate state, wordcode pcode, 1669 int how, int input, int output, int last1) 1670{ 1671 pid_t pid; 1672 int pipes[2]; 1673 1674 if (breaks || retflag) 1675 return; 1676 1677 /* In evaluated traps, don't modify the line number. */ 1678 if (!IN_EVAL_TRAP() && !ineval && WC_PIPE_LINENO(pcode)) 1679 lineno = WC_PIPE_LINENO(pcode) - 1; 1680 1681 if (pline_level == 1) { 1682 if ((how & Z_ASYNC) || (!sfcontext && !sourcelevel)) 1683 strcpy(list_pipe_text, 1684 getjobtext(state->prog, 1685 state->pc + (WC_PIPE_TYPE(pcode) == WC_PIPE_END ? 1686 0 : 1))); 1687 else 1688 list_pipe_text[0] = '\0'; 1689 } 1690 if (WC_PIPE_TYPE(pcode) == WC_PIPE_END) 1691 execcmd(state, input, output, how, last1 ? 1 : 2); 1692 else { 1693 int old_list_pipe = list_pipe; 1694 int subsh_close = -1; 1695 Wordcode next = state->pc + (*state->pc), pc; 1696 wordcode code; 1697 1698 state->pc++; 1699 for (pc = state->pc; wc_code(code = *pc) == WC_REDIR; 1700 pc += WC_REDIR_WORDS(code)); 1701 1702 if (mpipe(pipes) < 0) { 1703 /* FIXME */ 1704 } 1705 1706 /* if we are doing "foo | bar" where foo is a current * 1707 * shell command, do foo in a subshell and do the * 1708 * rest of the pipeline in the current shell. */ 1709 if (wc_code(code) >= WC_CURSH && (how & Z_SYNC)) { 1710 int synch[2]; 1711 struct timeval bgtime; 1712 1713 if (pipe(synch) < 0) { 1714 zerr("pipe failed: %e", errno); 1715 lastval = errflag = 1; 1716 return; 1717 } else if ((pid = zfork(&bgtime)) == -1) { 1718 close(synch[0]); 1719 close(synch[1]); 1720 lastval = errflag = 1; 1721 return; 1722 } else if (pid) { 1723 char dummy, *text; 1724 1725 text = getjobtext(state->prog, state->pc); 1726 addproc(pid, text, 0, &bgtime); 1727 close(synch[1]); 1728 read_loop(synch[0], &dummy, 1); 1729 close(synch[0]); 1730 } else { 1731 zclose(pipes[0]); 1732 close(synch[0]); 1733 entersubsh(((how & Z_ASYNC) ? ESUB_ASYNC : 0) 1734 | ESUB_PGRP | ESUB_KEEPTRAP); 1735 close(synch[1]); 1736 execcmd(state, input, pipes[1], how, 1); 1737 _exit(lastval); 1738 } 1739 } else { 1740 /* otherwise just do the pipeline normally. */ 1741 addfilelist(NULL, pipes[0]); 1742 subsh_close = pipes[0]; 1743 execcmd(state, input, pipes[1], how, 0); 1744 } 1745 zclose(pipes[1]); 1746 state->pc = next; 1747 1748 /* if another execpline() is invoked because the command is * 1749 * a list it must know that we're already in a pipeline */ 1750 cmdpush(CS_PIPE); 1751 list_pipe = 1; 1752 execpline2(state, *state->pc++, how, pipes[0], output, last1); 1753 list_pipe = old_list_pipe; 1754 cmdpop(); 1755 if (subsh_close != pipes[0]) 1756 zclose(pipes[0]); 1757 } 1758} 1759 1760/* make the argv array */ 1761 1762/**/ 1763static char ** 1764makecline(LinkList list) 1765{ 1766 LinkNode node; 1767 char **argv, **ptr; 1768 1769 /* A bigger argv is necessary for executing scripts */ 1770 ptr = argv = 2 + (char **) hcalloc((countlinknodes(list) + 4) * 1771 sizeof(char *)); 1772 1773 if (isset(XTRACE)) { 1774 if (!doneps4) 1775 printprompt4(); 1776 1777 for (node = firstnode(list); node; incnode(node)) { 1778 *ptr++ = (char *)getdata(node); 1779 quotedzputs(getdata(node), xtrerr); 1780 if (nextnode(node)) 1781 fputc(' ', xtrerr); 1782 } 1783 fputc('\n', xtrerr); 1784 fflush(xtrerr); 1785 } else { 1786 for (node = firstnode(list); node; incnode(node)) 1787 *ptr++ = (char *)getdata(node); 1788 } 1789 *ptr = NULL; 1790 return (argv); 1791} 1792 1793/**/ 1794mod_export void 1795untokenize(char *s) 1796{ 1797 if (*s) { 1798 int c; 1799 1800 while ((c = *s++)) 1801 if (itok(c)) { 1802 char *p = s - 1; 1803 1804 if (c != Nularg) 1805 *p++ = ztokens[c - Pound]; 1806 1807 while ((c = *s++)) { 1808 if (itok(c)) { 1809 if (c != Nularg) 1810 *p++ = ztokens[c - Pound]; 1811 } else 1812 *p++ = c; 1813 } 1814 *p = '\0'; 1815 break; 1816 } 1817 } 1818} 1819 1820 1821/* 1822 * Given a tokenized string, output it to standard output in 1823 * such a way that it's clear which tokens are active. 1824 * Hence Star becomes an unquoted "*", while a "*" becomes "\*". 1825 * 1826 * The code here is a kind of amalgamation of the tests in 1827 * zshtokenize() and untokenize() with some outputting. 1828 */ 1829 1830/**/ 1831void 1832quote_tokenized_output(char *str, FILE *file) 1833{ 1834 char *s = str; 1835 1836 for (; *s; s++) { 1837 switch (*s) { 1838 case Meta: 1839 putc(*++s ^ 32, file); 1840 continue; 1841 1842 case Nularg: 1843 /* Do nothing. I think. */ 1844 continue; 1845 1846 case '\\': 1847 case '<': 1848 case '>': 1849 case '(': 1850 case '|': 1851 case ')': 1852 case '^': 1853 case '#': 1854 case '~': 1855 case '[': 1856 case ']': 1857 case '*': 1858 case '?': 1859 case '$': 1860 case ' ': 1861 putc('\\', file); 1862 break; 1863 1864 case '\t': 1865 fputs("$'\\t'", file); 1866 continue; 1867 1868 case '\n': 1869 fputs("$'\\n'", file); 1870 continue; 1871 1872 case '\r': 1873 fputs("$'\\r'", file); 1874 continue; 1875 1876 case '=': 1877 if (s == str) 1878 putc('\\', file); 1879 break; 1880 1881 default: 1882 if (itok(*s)) { 1883 putc(ztokens[*s - Pound], file); 1884 continue; 1885 } 1886 break; 1887 } 1888 1889 putc(*s, file); 1890 } 1891} 1892 1893/* Check that we can use a parameter for allocating a file descriptor. */ 1894 1895static int 1896checkclobberparam(struct redir *f) 1897{ 1898 struct value vbuf; 1899 Value v; 1900 char *s = f->varid; 1901 int fd; 1902 1903 if (!s) 1904 return 1; 1905 1906 if (!(v = getvalue(&vbuf, &s, 0))) 1907 return 1; 1908 1909 if (v->pm->node.flags & PM_READONLY) { 1910 zwarn("can't allocate file descriptor to readonly parameter %s", 1911 f->varid); 1912 /* don't flag a system error for this */ 1913 errno = 0; 1914 return 0; 1915 } 1916 1917 /* 1918 * We can't clobber the value in the parameter if it's 1919 * already an opened file descriptor --- that means it's a decimal 1920 * integer corresponding to an opened file descriptor, 1921 * not merely an expression that evaluates to a file descriptor. 1922 */ 1923 if (!isset(CLOBBER) && (s = getstrvalue(v)) && 1924 (fd = (int)zstrtol(s, &s, 10)) >= 0 && !*s && 1925 fd <= max_zsh_fd && fdtable[fd] == FDT_EXTERNAL) { 1926 zwarn("can't clobber parameter %s containing file descriptor %d", 1927 f->varid, fd); 1928 /* don't flag a system error for this */ 1929 errno = 0; 1930 return 0; 1931 } 1932 return 1; 1933} 1934 1935/* Open a file for writing redirection */ 1936 1937/**/ 1938static int 1939clobber_open(struct redir *f) 1940{ 1941 struct stat buf; 1942 int fd, oerrno; 1943 1944 /* If clobbering, just open. */ 1945 if (isset(CLOBBER) || IS_CLOBBER_REDIR(f->type)) 1946 return open(unmeta(f->name), 1947 O_WRONLY | O_CREAT | O_TRUNC | O_NOCTTY, 0666); 1948 1949 /* If not clobbering, attempt to create file exclusively. */ 1950 if ((fd = open(unmeta(f->name), 1951 O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0666)) >= 0) 1952 return fd; 1953 1954 /* If that fails, we are still allowed to open non-regular files. * 1955 * Try opening, and if it's a regular file then close it again * 1956 * because we weren't supposed to open it. */ 1957 oerrno = errno; 1958 if ((fd = open(unmeta(f->name), O_WRONLY | O_NOCTTY)) != -1) { 1959 if(!fstat(fd, &buf) && !S_ISREG(buf.st_mode)) 1960 return fd; 1961 close(fd); 1962 } 1963 errno = oerrno; 1964 return -1; 1965} 1966 1967/* size of buffer for tee and cat processes */ 1968#define TCBUFSIZE 4092 1969 1970/* close an multio (success) */ 1971 1972/**/ 1973static void 1974closemn(struct multio **mfds, int fd, int type) 1975{ 1976 if (fd >= 0 && mfds[fd] && mfds[fd]->ct >= 2) { 1977 struct multio *mn = mfds[fd]; 1978 char buf[TCBUFSIZE]; 1979 int len, i; 1980 pid_t pid; 1981 struct timeval bgtime; 1982 1983 /* 1984 * We need to block SIGCHLD in case the process 1985 * we are spawning terminates before the job table 1986 * is set up to handle it. 1987 */ 1988 child_block(); 1989 if ((pid = zfork(&bgtime))) { 1990 for (i = 0; i < mn->ct; i++) 1991 zclose(mn->fds[i]); 1992 zclose(mn->pipe); 1993 if (pid == -1) { 1994 mfds[fd] = NULL; 1995 child_unblock(); 1996 return; 1997 } 1998 mn->ct = 1; 1999 mn->fds[0] = fd; 2000 addproc(pid, NULL, 1, &bgtime); 2001 child_unblock(); 2002 return; 2003 } 2004 /* pid == 0 */ 2005 child_unblock(); 2006 closeallelse(mn); 2007 if (mn->rflag) { 2008 /* tee process */ 2009 while ((len = read(mn->pipe, buf, TCBUFSIZE)) != 0) { 2010 if (len < 0) { 2011 if (errno == EINTR) 2012 continue; 2013 else 2014 break; 2015 } 2016 for (i = 0; i < mn->ct; i++) 2017 write_loop(mn->fds[i], buf, len); 2018 } 2019 } else { 2020 /* cat process */ 2021 for (i = 0; i < mn->ct; i++) 2022 while ((len = read(mn->fds[i], buf, TCBUFSIZE)) != 0) { 2023 if (len < 0) { 2024 if (errno == EINTR) 2025 continue; 2026 else 2027 break; 2028 } 2029 write_loop(mn->pipe, buf, len); 2030 } 2031 } 2032 _exit(0); 2033 } else if (fd >= 0 && type == REDIR_CLOSE) 2034 mfds[fd] = NULL; 2035} 2036 2037/* close all the mnodes (failure) */ 2038 2039/**/ 2040static void 2041closemnodes(struct multio **mfds) 2042{ 2043 int i, j; 2044 2045 for (i = 0; i < 10; i++) 2046 if (mfds[i]) { 2047 for (j = 0; j < mfds[i]->ct; j++) 2048 zclose(mfds[i]->fds[j]); 2049 mfds[i] = NULL; 2050 } 2051} 2052 2053/**/ 2054static void 2055closeallelse(struct multio *mn) 2056{ 2057 int i, j; 2058 long openmax; 2059 2060 openmax = fdtable_size; 2061 2062 for (i = 0; i < openmax; i++) 2063 if (mn->pipe != i) { 2064 for (j = 0; j < mn->ct; j++) 2065 if (mn->fds[j] == i) 2066 break; 2067 if (j == mn->ct) 2068 zclose(i); 2069 } 2070} 2071 2072/* 2073 * A multio is a list of fds associated with a certain fd. 2074 * Thus if you do "foo >bar >ble", the multio for fd 1 will have 2075 * two fds, the result of open("bar",...), and the result of 2076 * open("ble",....). 2077 */ 2078 2079/* 2080 * Add a fd to an multio. fd1 must be < 10, and may be in any state. 2081 * fd2 must be open, and is `consumed' by this function. Note that 2082 * fd1 == fd2 is possible, and indicates that fd1 was really closed. 2083 * We effectively do `fd2 = movefd(fd2)' at the beginning of this 2084 * function, but in most cases we can avoid an extra dup by delaying 2085 * the movefd: we only >need< to move it if we're actually doing a 2086 * multiple redirection. 2087 * 2088 * If varid is not NULL, we open an fd above 10 and set the parameter 2089 * named varid to that value. fd1 is not used. 2090 */ 2091 2092/**/ 2093static void 2094addfd(int forked, int *save, struct multio **mfds, int fd1, int fd2, int rflag, 2095 char *varid) 2096{ 2097 int pipes[2]; 2098 2099 if (varid) { 2100 /* fd will be over 10, don't touch mfds */ 2101 fd1 = movefd(fd2); 2102 if (fd1 == -1) { 2103 zerr("cannot moved fd %d: %e", fd2, errno); 2104 return; 2105 } else { 2106 fdtable[fd1] = FDT_EXTERNAL; 2107 setiparam(varid, (zlong)fd1); 2108 /* 2109 * If setting the parameter failed, close the fd else 2110 * it will leak. 2111 */ 2112 if (errflag) 2113 zclose(fd1); 2114 } 2115 } else if (!mfds[fd1] || unset(MULTIOS)) { 2116 if(!mfds[fd1]) { /* starting a new multio */ 2117 mfds[fd1] = (struct multio *) zhalloc(sizeof(struct multio)); 2118 if (!forked && save[fd1] == -2) { 2119 if (fd1 == fd2) 2120 save[fd1] = -1; 2121 else { 2122 int fdN = movefd(fd1); 2123 /* 2124 * fd1 may already be closed here, so 2125 * ignore bad file descriptor error 2126 */ 2127 if (fdN < 0 && errno != EBADF) { 2128 zerr("cannot duplicate fd %d: %e", fd1, errno); 2129 mfds[fd1] = NULL; 2130 closemnodes(mfds); 2131 return; 2132 } 2133 save[fd1] = fdN; 2134 } 2135 } 2136 } 2137 if (!varid) 2138 redup(fd2, fd1); 2139 mfds[fd1]->ct = 1; 2140 mfds[fd1]->fds[0] = fd1; 2141 mfds[fd1]->rflag = rflag; 2142 } else { 2143 if (mfds[fd1]->rflag != rflag) { 2144 zerr("file mode mismatch on fd %d", fd1); 2145 closemnodes(mfds); 2146 return; 2147 } 2148 if (mfds[fd1]->ct == 1) { /* split the stream */ 2149 int fdN = movefd(fd1); 2150 if (fdN < 0) { 2151 zerr("multio failed for fd %d: %e", fd1, errno); 2152 closemnodes(mfds); 2153 return; 2154 } 2155 mfds[fd1]->fds[0] = fdN; 2156 fdN = movefd(fd2); 2157 if (fdN < 0) { 2158 zerr("multio failed for fd %d: %e", fd2, errno); 2159 closemnodes(mfds); 2160 return; 2161 } 2162 mfds[fd1]->fds[1] = fdN; 2163 if (mpipe(pipes) < 0) { 2164 zerr("multio failed for fd %d: %e", fd2, errno); 2165 closemnodes(mfds); 2166 return; 2167 } 2168 mfds[fd1]->pipe = pipes[1 - rflag]; 2169 redup(pipes[rflag], fd1); 2170 mfds[fd1]->ct = 2; 2171 } else { /* add another fd to an already split stream */ 2172 int fdN; 2173 if(!(mfds[fd1]->ct % MULTIOUNIT)) { 2174 int new = sizeof(struct multio) + sizeof(int) * mfds[fd1]->ct; 2175 int old = new - sizeof(int) * MULTIOUNIT; 2176 mfds[fd1] = hrealloc((char *)mfds[fd1], old, new); 2177 } 2178 if ((fdN = movefd(fd2)) < 0) { 2179 zerr("multio failed for fd %d: %e", fd2, errno); 2180 closemnodes(mfds); 2181 return; 2182 } 2183 mfds[fd1]->fds[mfds[fd1]->ct++] = fdN; 2184 } 2185 } 2186} 2187 2188/**/ 2189static void 2190addvars(Estate state, Wordcode pc, int addflags) 2191{ 2192 LinkList vl; 2193 int xtr, isstr, htok = 0; 2194 char **arr, **ptr, *name; 2195 int flags; 2196 2197 Wordcode opc = state->pc; 2198 wordcode ac; 2199 local_list1(svl); 2200 2201 /* 2202 * Warn when creating a global without using typeset -g in a 2203 * function. Don't do this if there is a list of variables marked 2204 * to be restored after the command, since then the assignment 2205 * is implicitly scoped. 2206 */ 2207 flags = (!(addflags & ADDVAR_RESTORE) && 2208 locallevel > 0 && isset(WARNCREATEGLOBAL)) ? 2209 ASSPM_WARN_CREATE : 0; 2210 xtr = isset(XTRACE); 2211 if (xtr) { 2212 printprompt4(); 2213 doneps4 = 1; 2214 } 2215 state->pc = pc; 2216 while (wc_code(ac = *state->pc++) == WC_ASSIGN) { 2217 int myflags = flags; 2218 name = ecgetstr(state, EC_DUPTOK, &htok); 2219 if (htok) 2220 untokenize(name); 2221 if (WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC) 2222 myflags |= ASSPM_AUGMENT; 2223 if (xtr) 2224 fprintf(xtrerr, 2225 WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC ? "%s+=" : "%s=", name); 2226 if ((isstr = (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR))) { 2227 init_list1(svl, ecgetstr(state, EC_DUPTOK, &htok)); 2228 vl = &svl; 2229 } else 2230 vl = ecgetlist(state, WC_ASSIGN_NUM(ac), EC_DUPTOK, &htok); 2231 2232 if (vl && htok) { 2233 prefork(vl, (isstr ? (PREFORK_SINGLE|PREFORK_ASSIGN) : 2234 PREFORK_ASSIGN)); 2235 if (errflag) { 2236 state->pc = opc; 2237 return; 2238 } 2239 if (isset(GLOBASSIGN) || !isstr) 2240 globlist(vl, 0); 2241 if (errflag) { 2242 state->pc = opc; 2243 return; 2244 } 2245 } 2246 if (isstr && (empty(vl) || !nextnode(firstnode(vl)))) { 2247 Param pm; 2248 char *val; 2249 int allexp; 2250 2251 if (empty(vl)) 2252 val = ztrdup(""); 2253 else { 2254 untokenize(peekfirst(vl)); 2255 val = ztrdup(ugetnode(vl)); 2256 } 2257 if (xtr) { 2258 quotedzputs(val, xtrerr); 2259 fputc(' ', xtrerr); 2260 } 2261 if ((addflags & ADDVAR_EXPORT) && !strchr(name, '[')) { 2262 if ((addflags & ADDVAR_RESTRICT) && isset(RESTRICTED) && 2263 (pm = (Param) paramtab->removenode(paramtab, name)) && 2264 (pm->node.flags & PM_RESTRICTED)) { 2265 zerr("%s: restricted", pm->node.nam); 2266 zsfree(val); 2267 state->pc = opc; 2268 return; 2269 } 2270 if (strcmp(name, "STTY") == 0) { 2271 zsfree(STTYval); 2272 STTYval = ztrdup(val); 2273 } 2274 allexp = opts[ALLEXPORT]; 2275 opts[ALLEXPORT] = 1; 2276 pm = assignsparam(name, val, myflags); 2277 opts[ALLEXPORT] = allexp; 2278 } else 2279 pm = assignsparam(name, val, myflags); 2280 if (errflag) { 2281 state->pc = opc; 2282 return; 2283 } 2284 continue; 2285 } 2286 if (vl) { 2287 ptr = arr = (char **) zalloc(sizeof(char **) * 2288 (countlinknodes(vl) + 1)); 2289 2290 while (nonempty(vl)) 2291 *ptr++ = ztrdup((char *) ugetnode(vl)); 2292 } else 2293 ptr = arr = (char **) zalloc(sizeof(char **)); 2294 2295 *ptr = NULL; 2296 if (xtr) { 2297 fprintf(xtrerr, "( "); 2298 for (ptr = arr; *ptr; ptr++) { 2299 quotedzputs(*ptr, xtrerr); 2300 fputc(' ', xtrerr); 2301 } 2302 fprintf(xtrerr, ") "); 2303 } 2304 assignaparam(name, arr, myflags); 2305 if (errflag) { 2306 state->pc = opc; 2307 return; 2308 } 2309 } 2310 state->pc = opc; 2311} 2312 2313/**/ 2314void 2315setunderscore(char *str) 2316{ 2317 if (str && *str) { 2318 int l = strlen(str) + 1, nl = (l + 31) & ~31; 2319 2320 if (nl > underscorelen || (underscorelen - nl) > 64) { 2321 zfree(zunderscore, underscorelen); 2322 zunderscore = (char *) zalloc(underscorelen = nl); 2323 } 2324 strcpy(zunderscore, str); 2325 underscoreused = l; 2326 } else { 2327 if (underscorelen > 128) { 2328 zfree(zunderscore, underscorelen); 2329 zunderscore = (char *) zalloc(underscorelen = 32); 2330 } 2331 *zunderscore = '\0'; 2332 underscoreused = 1; 2333 } 2334} 2335 2336/* These describe the type of expansions that need to be done on the words 2337 * used in the thing we are about to execute. They are set in execcmd() and 2338 * used in execsubst() which might be called from one of the functions 2339 * called from execcmd() (like execfor() and so on). */ 2340 2341static int esprefork, esglob = 1; 2342 2343/**/ 2344void 2345execsubst(LinkList strs) 2346{ 2347 if (strs) { 2348 prefork(strs, esprefork); 2349 if (esglob) { 2350 LinkList ostrs = strs; 2351 globlist(strs, 0); 2352 strs = ostrs; 2353 } 2354 } 2355} 2356 2357/* 2358 * Check if a builtin requires an autoload and if so 2359 * deal with it. This may return NULL. 2360 */ 2361 2362/**/ 2363static HashNode 2364resolvebuiltin(const char *cmdarg, HashNode hn) 2365{ 2366 if (!((Builtin) hn)->handlerfunc) { 2367 char *modname = dupstring(((Builtin) hn)->optstr); 2368 /* 2369 * Ensure the module is loaded and the 2370 * feature corresponding to the builtin 2371 * is enabled. 2372 */ 2373 (void)ensurefeature(modname, "b:", 2374 (hn->flags & BINF_AUTOALL) ? NULL : 2375 hn->nam); 2376 hn = builtintab->getnode(builtintab, cmdarg); 2377 if (!hn) { 2378 lastval = 1; 2379 zerr("autoloading module %s failed to define builtin: %s", 2380 modname, cmdarg); 2381 return NULL; 2382 } 2383 } 2384 return hn; 2385} 2386 2387/**/ 2388static void 2389execcmd(Estate state, int input, int output, int how, int last1) 2390{ 2391 HashNode hn = NULL; 2392 LinkList args, filelist = NULL; 2393 LinkNode node; 2394 Redir fn; 2395 struct multio *mfds[10]; 2396 char *text; 2397 int save[10]; 2398 int fil, dfil, is_cursh, type, do_exec = 0, redir_err = 0, i, htok = 0; 2399 int nullexec = 0, assign = 0, forked = 0; 2400 int is_shfunc = 0, is_builtin = 0, is_exec = 0, use_defpath = 0; 2401 /* Various flags to the command. */ 2402 int cflags = 0, orig_cflags = 0, checked = 0, oautocont = -1; 2403 LinkList redir; 2404 wordcode code; 2405 Wordcode beg = state->pc, varspc; 2406 FILE *oxtrerr = xtrerr, *newxtrerr = NULL; 2407 2408 doneps4 = 0; 2409 redir = (wc_code(*state->pc) == WC_REDIR ? ecgetredirs(state) : NULL); 2410 if (wc_code(*state->pc) == WC_ASSIGN) { 2411 cmdoutval = 0; 2412 varspc = state->pc; 2413 while (wc_code((code = *state->pc)) == WC_ASSIGN) 2414 state->pc += (WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR ? 2415 3 : WC_ASSIGN_NUM(code) + 2); 2416 } else 2417 varspc = NULL; 2418 2419 code = *state->pc++; 2420 2421 type = wc_code(code); 2422 2423 /* It would be nice if we could use EC_DUPTOK instead of EC_DUP here. 2424 * But for that we would need to check/change all builtins so that 2425 * they don't modify their argument strings. */ 2426 args = (type == WC_SIMPLE ? 2427 ecgetlist(state, WC_SIMPLE_ARGC(code), EC_DUP, &htok) : NULL); 2428 /* 2429 * If assignment but no command get the status from variable 2430 * assignment. 2431 */ 2432 if (!args && varspc) 2433 lastval = errflag ? errflag : cmdoutval; 2434 /* 2435 * If there are arguments, we should reset the status for the 2436 * command before execution---unless we are using the result of a 2437 * command substitution, which will be indicated by setting 2438 * use_cmdoutval to 1. We haven't kicked those off yet, so 2439 * there's no race. 2440 */ 2441 use_cmdoutval = !args; 2442 2443 for (i = 0; i < 10; i++) { 2444 save[i] = -2; 2445 mfds[i] = NULL; 2446 } 2447 2448 /* If the command begins with `%', then assume it is a * 2449 * reference to a job in the job table. */ 2450 if (type == WC_SIMPLE && args && nonempty(args) && 2451 *(char *)peekfirst(args) == '%') { 2452 if (how & Z_DISOWN) { 2453 oautocont = opts[AUTOCONTINUE]; 2454 opts[AUTOCONTINUE] = 1; 2455 } 2456 pushnode(args, dupstring((how & Z_DISOWN) 2457 ? "disown" : (how & Z_ASYNC) ? "bg" : "fg")); 2458 how = Z_SYNC; 2459 } 2460 2461 /* If AUTORESUME is set, the command is SIMPLE, and doesn't have * 2462 * any redirections, then check if it matches as a prefix of a * 2463 * job currently in the job table. If it does, then we treat it * 2464 * as a command to resume this job. */ 2465 if (isset(AUTORESUME) && type == WC_SIMPLE && (how & Z_SYNC) && 2466 args && nonempty(args) && (!redir || empty(redir)) && !input && 2467 !nextnode(firstnode(args))) { 2468 if (unset(NOTIFY)) 2469 scanjobs(); 2470 if (findjobnam(peekfirst(args)) != -1) 2471 pushnode(args, dupstring("fg")); 2472 } 2473 2474 /* Check if it's a builtin needing automatic MAGIC_EQUALS_SUBST * 2475 * handling. Things like typeset need this. We can't detect the * 2476 * command if it contains some tokens (e.g. x=ex; ${x}port), so this * 2477 * only works in simple cases. has_token() is called to make sure * 2478 * this really is a simple case. */ 2479 if (type == WC_SIMPLE) { 2480 while (args && nonempty(args)) { 2481 char *cmdarg = (char *) peekfirst(args); 2482 checked = !has_token(cmdarg); 2483 if (!checked) 2484 break; 2485 if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) && 2486 (hn = shfunctab->getnode(shfunctab, cmdarg))) { 2487 is_shfunc = 1; 2488 break; 2489 } 2490 if (!(hn = builtintab->getnode(builtintab, cmdarg))) { 2491 checked = !(cflags & BINF_BUILTIN); 2492 break; 2493 } 2494 orig_cflags |= cflags; 2495 cflags &= ~BINF_BUILTIN & ~BINF_COMMAND; 2496 cflags |= hn->flags; 2497 if (!(hn->flags & BINF_PREFIX)) { 2498 is_builtin = 1; 2499 2500 /* autoload the builtin if necessary */ 2501 if (!(hn = resolvebuiltin(cmdarg, hn))) 2502 return; 2503 assign = (hn->flags & BINF_MAGICEQUALS); 2504 break; 2505 } 2506 checked = 0; 2507 if ((cflags & BINF_COMMAND) && nextnode(firstnode(args))) { 2508 /* check for options to command builtin */ 2509 char *next = (char *) getdata(nextnode(firstnode(args))); 2510 char *cmdopt; 2511 if (next && *next == '-' && strlen(next) == 2 && 2512 (cmdopt = strchr("pvV", next[1]))) 2513 { 2514 if (*cmdopt == 'p') { 2515 uremnode(args, firstnode(args)); 2516 use_defpath = 1; 2517 if (nextnode(firstnode(args))) 2518 next = (char *) getdata(nextnode(firstnode(args))); 2519 } else { 2520 hn = &commandbn.node; 2521 is_builtin = 1; 2522 break; 2523 } 2524 } 2525 if (!strcmp(next, "--")) 2526 uremnode(args, firstnode(args)); 2527 } 2528 if ((cflags & BINF_EXEC) && nextnode(firstnode(args))) { 2529 /* 2530 * Check for compatibility options to exec builtin. 2531 * It would be nice to do these more generically, 2532 * but currently we don't have a mechanism for 2533 * precommand modifiers. 2534 */ 2535 char *next = (char *) getdata(nextnode(firstnode(args))); 2536 char *cmdopt, *exec_argv0 = NULL; 2537 /* 2538 * Careful here: we want to make sure a final dash 2539 * is passed through in order that it still behaves 2540 * as a precommand modifier (zsh equivalent of -l). 2541 * It has to be last, but I think that's OK since 2542 * people aren't likely to mix the option style 2543 * with the zsh style. 2544 */ 2545 while (next && *next == '-' && strlen(next) >= 2) { 2546 if (!firstnode(args)) { 2547 zerr("exec requires a command to execute"); 2548 errflag = lastval = 1; 2549 goto done; 2550 } 2551 uremnode(args, firstnode(args)); 2552 if (!strcmp(next, "--")) 2553 break; 2554 for (cmdopt = &next[1]; *cmdopt; ++cmdopt) { 2555 switch (*cmdopt) { 2556 case 'a': 2557 /* argument is ARGV0 string */ 2558 if (cmdopt[1]) { 2559 exec_argv0 = cmdopt+1; 2560 /* position on last non-NULL character */ 2561 cmdopt += strlen(cmdopt+1); 2562 } else { 2563 if (!firstnode(args)) { 2564 zerr("exec requires a command to execute"); 2565 errflag = lastval = 1; 2566 goto done; 2567 } 2568 if (!nextnode(firstnode(args))) { 2569 zerr("exec flag -a requires a parameter"); 2570 errflag = lastval = 1; 2571 goto done; 2572 } 2573 exec_argv0 = (char *) 2574 getdata(nextnode(firstnode(args))); 2575 uremnode(args, firstnode(args)); 2576 } 2577 break; 2578 case 'c': 2579 cflags |= BINF_CLEARENV; 2580 break; 2581 case 'l': 2582 cflags |= BINF_DASH; 2583 break; 2584 default: 2585 zerr("unknown exec flag -%c", *cmdopt); 2586 errflag = lastval = 1; 2587 return; 2588 } 2589 } 2590 if (firstnode(args) && nextnode(firstnode(args))) 2591 next = (char *) getdata(nextnode(firstnode(args))); 2592 } 2593 if (exec_argv0) { 2594 char *str, *s; 2595 size_t sz = strlen(exec_argv0); 2596 str = s = zalloc(5 + 1 + sz + 1); 2597 strcpy(s, "ARGV0="); 2598 s+=6; 2599 strcpy(s, exec_argv0); 2600 zputenv(str); 2601 } 2602 } 2603 uremnode(args, firstnode(args)); 2604 hn = NULL; 2605 if ((cflags & BINF_COMMAND) && unset(POSIXBUILTINS)) 2606 break; 2607 } 2608 } 2609 2610 /* Do prefork substitutions */ 2611 esprefork = (assign || isset(MAGICEQUALSUBST)) ? PREFORK_TYPESET : 0; 2612 if (args && htok) 2613 prefork(args, esprefork); 2614 2615 if (type == WC_SIMPLE) { 2616 int unglobbed = 0; 2617 2618 for (;;) { 2619 char *cmdarg; 2620 2621 if (!(cflags & BINF_NOGLOB)) 2622 while (!checked && !errflag && args && nonempty(args) && 2623 has_token((char *) peekfirst(args))) 2624 zglob(args, firstnode(args), 0); 2625 else if (!unglobbed) { 2626 for (node = firstnode(args); node; incnode(node)) 2627 untokenize((char *) getdata(node)); 2628 unglobbed = 1; 2629 } 2630 2631 /* Current shell should not fork unless the * 2632 * exec occurs at the end of a pipeline. */ 2633 if ((cflags & BINF_EXEC) && last1) 2634 do_exec = 1; 2635 2636 /* Empty command */ 2637 if (!args || empty(args)) { 2638 if (redir && nonempty(redir)) { 2639 if (do_exec) { 2640 /* Was this "exec < foobar"? */ 2641 nullexec = 1; 2642 break; 2643 } else if (varspc) { 2644 nullexec = 2; 2645 break; 2646 } else if (!nullcmd || !*nullcmd || opts[CSHNULLCMD] || 2647 (cflags & BINF_PREFIX)) { 2648 zerr("redirection with no command"); 2649 errflag = lastval = 1; 2650 return; 2651 } else if (!nullcmd || !*nullcmd || opts[SHNULLCMD]) { 2652 if (!args) 2653 args = newlinklist(); 2654 addlinknode(args, dupstring(":")); 2655 } else if (readnullcmd && *readnullcmd && 2656 ((Redir) peekfirst(redir))->type == REDIR_READ && 2657 !nextnode(firstnode(redir))) { 2658 if (!args) 2659 args = newlinklist(); 2660 addlinknode(args, dupstring(readnullcmd)); 2661 } else { 2662 if (!args) 2663 args = newlinklist(); 2664 addlinknode(args, dupstring(nullcmd)); 2665 } 2666 } else if ((cflags & BINF_PREFIX) && (cflags & BINF_COMMAND)) { 2667 lastval = 0; 2668 return; 2669 } else { 2670 /* 2671 * No arguments. Reset the status if there were 2672 * arguments before and no command substitution 2673 * has provided a status. 2674 */ 2675 cmdoutval = use_cmdoutval ? lastval : 0; 2676 if (varspc) 2677 addvars(state, varspc, 0); 2678 if (errflag) 2679 lastval = errflag; 2680 else 2681 lastval = cmdoutval; 2682 if (isset(XTRACE)) { 2683 fputc('\n', xtrerr); 2684 fflush(xtrerr); 2685 } 2686 return; 2687 } 2688 } else if (isset(RESTRICTED) && (cflags & BINF_EXEC) && do_exec) { 2689 zerrnam("exec", "%s: restricted", 2690 (char *) getdata(firstnode(args))); 2691 lastval = 1; 2692 return; 2693 } 2694 2695 /* 2696 * Quit looking for a command if: 2697 * - there was an error; or 2698 * - we checked the simple cases needing MAGIC_EQUAL_SUBST; or 2699 * - we know we already found a builtin (because either: 2700 * - we loaded a builtin from a module, or 2701 * - we have determined there are options which would 2702 * require us to use the "command" builtin); or 2703 * - we aren't using POSIX and so BINF_COMMAND indicates a zsh 2704 * precommand modifier is being used in place of the builtin 2705 */ 2706 if (errflag || checked || is_builtin || 2707 (unset(POSIXBUILTINS) && (cflags & BINF_COMMAND))) 2708 break; 2709 2710 cmdarg = (char *) peekfirst(args); 2711 if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) && 2712 (hn = shfunctab->getnode(shfunctab, cmdarg))) { 2713 is_shfunc = 1; 2714 break; 2715 } 2716 if (!(hn = builtintab->getnode(builtintab, cmdarg))) { 2717 if (cflags & BINF_BUILTIN) { 2718 zwarn("no such builtin: %s", cmdarg); 2719 lastval = 1; 2720 if (oautocont >= 0) 2721 opts[AUTOCONTINUE] = oautocont; 2722 return; 2723 } 2724 break; 2725 } 2726 if (!(hn->flags & BINF_PREFIX)) { 2727 is_builtin = 1; 2728 2729 /* autoload the builtin if necessary */ 2730 if (!(hn = resolvebuiltin(cmdarg, hn))) 2731 return; 2732 break; 2733 } 2734 cflags &= ~BINF_BUILTIN & ~BINF_COMMAND; 2735 cflags |= hn->flags; 2736 uremnode(args, firstnode(args)); 2737 hn = NULL; 2738 } 2739 } 2740 2741 if (errflag) { 2742 lastval = 1; 2743 if (oautocont >= 0) 2744 opts[AUTOCONTINUE] = oautocont; 2745 return; 2746 } 2747 2748 /* Get the text associated with this command. */ 2749 if ((how & Z_ASYNC) || 2750 (!sfcontext && !sourcelevel && (jobbing || (how & Z_TIMED)))) 2751 text = getjobtext(state->prog, beg); 2752 else 2753 text = NULL; 2754 2755 /* Set up special parameter $_ */ 2756 2757 setunderscore((args && nonempty(args)) ? ((char *) getdata(lastnode(args))) : ""); 2758 2759 /* Warn about "rm *" */ 2760 if (type == WC_SIMPLE && interact && unset(RMSTARSILENT) && 2761 isset(SHINSTDIN) && args && nonempty(args) && 2762 nextnode(firstnode(args)) && !strcmp(peekfirst(args), "rm")) { 2763 LinkNode node, next; 2764 2765 for (node = nextnode(firstnode(args)); node && !errflag; node = next) { 2766 char *s = (char *) getdata(node); 2767 int l = strlen(s); 2768 2769 next = nextnode(node); 2770 if (s[0] == Star && !s[1]) { 2771 if (!checkrmall(pwd)) 2772 uremnode(args, node); 2773 } else if (l > 2 && s[l - 2] == '/' && s[l - 1] == Star) { 2774 char t = s[l - 2]; 2775 2776 s[l - 2] = 0; 2777 if (!checkrmall(s)) 2778 uremnode(args, node); 2779 s[l - 2] = t; 2780 } 2781 } 2782 if (!nextnode(firstnode(args))) 2783 errflag = 1; 2784 } 2785 2786 if (errflag) { 2787 lastval = 1; 2788 if (oautocont >= 0) 2789 opts[AUTOCONTINUE] = oautocont; 2790 return; 2791 } 2792 2793 if (type == WC_SIMPLE && !nullexec) { 2794 char *s; 2795 char trycd = (isset(AUTOCD) && isset(SHINSTDIN) && 2796 (!redir || empty(redir)) && args && !empty(args) && 2797 !nextnode(firstnode(args)) && *(char *)peekfirst(args)); 2798 2799 DPUTS((!args || empty(args)), "BUG: empty(args) in exec.c"); 2800 if (!hn) { 2801 /* Resolve external commands */ 2802 char *cmdarg = (char *) peekfirst(args); 2803 char **checkpath = pathchecked; 2804 int dohashcmd = isset(HASHCMDS); 2805 2806 hn = cmdnamtab->getnode(cmdnamtab, cmdarg); 2807 if (hn && trycd && !isreallycom((Cmdnam)hn)) { 2808 if (!(((Cmdnam)hn)->node.flags & HASHED)) { 2809 checkpath = path; 2810 dohashcmd = 1; 2811 } 2812 cmdnamtab->removenode(cmdnamtab, cmdarg); 2813 cmdnamtab->freenode(hn); 2814 hn = NULL; 2815 } 2816 if (!hn && dohashcmd && strcmp(cmdarg, "..")) { 2817 for (s = cmdarg; *s && *s != '/'; s++); 2818 if (!*s) 2819 hn = (HashNode) hashcmd(cmdarg, checkpath); 2820 } 2821 } 2822 2823 /* If no command found yet, see if it * 2824 * is a directory we should AUTOCD to. */ 2825 if (!hn && trycd && (s = cancd(peekfirst(args)))) { 2826 peekfirst(args) = (void *) s; 2827 pushnode(args, dupstring("cd")); 2828 if ((hn = builtintab->getnode(builtintab, "cd"))) 2829 is_builtin = 1; 2830 } 2831 } 2832 2833 /* This is nonzero if the command is a current shell procedure? */ 2834 is_cursh = (is_builtin || is_shfunc || nullexec || type >= WC_CURSH); 2835 2836 /************************************************************************** 2837 * Do we need to fork? We need to fork if: * 2838 * 1) The command is supposed to run in the background. (or) * 2839 * 2) There is no `exec' flag, and either: * 2840 * a) This is a builtin or shell function with output piped somewhere. * 2841 * b) This is an external command and we can't do a `fake exec'. * 2842 * * 2843 * A `fake exec' is possible if we have all the following conditions: * 2844 * 1) last1 flag is 1. This indicates that the current shell will not * 2845 * be needed after the current command. This is typically the case * 2846 * when the command is the last stage in a subshell, or is the * 2847 * last command after the option `-c'. * 2848 * 2) We don't have any traps set. * 2849 * 3) We don't have any files to delete. * 2850 * * 2851 * The condition above for a `fake exec' will also work for a current * 2852 * shell command such as a builtin, but doesn't really buy us anything * 2853 * (doesn't save us a process), since it is already running in the * 2854 * current shell. * 2855 **************************************************************************/ 2856 2857 if ((how & Z_ASYNC) || 2858 (!do_exec && 2859 (((is_builtin || is_shfunc) && output) || 2860 (!is_cursh && (last1 != 1 || nsigtrapped || havefiles() || 2861 fdtable_flocks))))) { 2862 2863 pid_t pid; 2864 int synch[2], flags; 2865 char dummy; 2866 struct timeval bgtime; 2867 2868 child_block(); 2869 2870 if (pipe(synch) < 0) { 2871 zerr("pipe failed: %e", errno); 2872 goto fatal; 2873 } else if ((pid = zfork(&bgtime)) == -1) { 2874 close(synch[0]); 2875 close(synch[1]); 2876 lastval = errflag = 1; 2877 goto fatal; 2878 } 2879 if (pid) { 2880 2881 close(synch[1]); 2882 read_loop(synch[0], &dummy, 1); 2883 close(synch[0]); 2884 if (how & Z_ASYNC) { 2885 lastpid = (zlong) pid; 2886 /* indicate it's possible to set status for lastpid */ 2887 lastpid_status = -2L; 2888 } else if (!jobtab[thisjob].stty_in_env && varspc) { 2889 /* search for STTY=... */ 2890 Wordcode p = varspc; 2891 wordcode ac; 2892 2893 while (wc_code(ac = *p) == WC_ASSIGN) { 2894 if (!strcmp(ecrawstr(state->prog, p + 1, NULL), "STTY")) { 2895 jobtab[thisjob].stty_in_env = 1; 2896 break; 2897 } 2898 p += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ? 2899 3 : WC_ASSIGN_NUM(ac) + 2); 2900 } 2901 } 2902 addproc(pid, text, 0, &bgtime); 2903 if (oautocont >= 0) 2904 opts[AUTOCONTINUE] = oautocont; 2905 return; 2906 } 2907 /* pid == 0 */ 2908 close(synch[0]); 2909 flags = ((how & Z_ASYNC) ? ESUB_ASYNC : 0) | ESUB_PGRP; 2910 if ((type != WC_SUBSH) && !(how & Z_ASYNC)) 2911 flags |= ESUB_KEEPTRAP; 2912 if (type == WC_SUBSH && !(how & Z_ASYNC)) 2913 flags |= ESUB_JOB_CONTROL; 2914 filelist = jobtab[thisjob].filelist; 2915 entersubsh(flags); 2916 close(synch[1]); 2917 forked = 1; 2918 if (sigtrapped[SIGINT] & ZSIG_IGNORED) 2919 holdintr(); 2920#ifdef HAVE_NICE 2921 /* Check if we should run background jobs at a lower priority. */ 2922 if ((how & Z_ASYNC) && isset(BGNICE)) 2923 if (nice(5) < 0) 2924 zwarn("nice(5) failed: %e", errno); 2925#endif /* HAVE_NICE */ 2926 2927 } else if (is_cursh) { 2928 /* This is a current shell procedure that didn't need to fork. * 2929 * This includes current shell procedures that are being exec'ed, * 2930 * as well as null execs. */ 2931 jobtab[thisjob].stat |= STAT_CURSH; 2932 if (!jobtab[thisjob].procs) 2933 jobtab[thisjob].stat |= STAT_NOPRINT; 2934 if (is_builtin) 2935 jobtab[thisjob].stat |= STAT_BUILTIN; 2936 } else { 2937 /* This is an exec (real or fake) for an external command. * 2938 * Note that any form of exec means that the subshell is fake * 2939 * (but we may be in a subshell already). */ 2940 is_exec = 1; 2941 } 2942 2943 if ((esglob = !(cflags & BINF_NOGLOB)) && args && htok) { 2944 LinkList oargs = args; 2945 globlist(args, 0); 2946 args = oargs; 2947 } 2948 if (errflag) { 2949 lastval = 1; 2950 goto err; 2951 } 2952 2953 /* Make a copy of stderr for xtrace output before redirecting */ 2954 fflush(xtrerr); 2955 if (isset(XTRACE) && xtrerr == stderr && 2956 (type < WC_SUBSH || type == WC_TIMED)) { 2957 if ((newxtrerr = fdopen(movefd(dup(fileno(stderr))), "w"))) { 2958 xtrerr = newxtrerr; 2959 fdtable[fileno(xtrerr)] = FDT_XTRACE; 2960 } 2961 } 2962 2963 /* Add pipeline input/output to mnodes */ 2964 if (input) 2965 addfd(forked, save, mfds, 0, input, 0, NULL); 2966 if (output) 2967 addfd(forked, save, mfds, 1, output, 1, NULL); 2968 2969 /* Do process substitutions */ 2970 if (redir) 2971 spawnpipes(redir, nullexec); 2972 2973 /* Do io redirections */ 2974 while (redir && nonempty(redir)) { 2975 fn = (Redir) ugetnode(redir); 2976 2977 DPUTS(fn->type == REDIR_HEREDOC || fn->type == REDIR_HEREDOCDASH, 2978 "BUG: unexpanded here document"); 2979 if (fn->type == REDIR_INPIPE) { 2980 if (!checkclobberparam(fn) || fn->fd2 == -1) { 2981 if (fn->fd2 != -1) 2982 zclose(fn->fd2); 2983 closemnodes(mfds); 2984 fixfds(save); 2985 execerr(); 2986 } 2987 addfd(forked, save, mfds, fn->fd1, fn->fd2, 0, fn->varid); 2988 } else if (fn->type == REDIR_OUTPIPE) { 2989 if (!checkclobberparam(fn) || fn->fd2 == -1) { 2990 if (fn->fd2 != -1) 2991 zclose(fn->fd2); 2992 closemnodes(mfds); 2993 fixfds(save); 2994 execerr(); 2995 } 2996 addfd(forked, save, mfds, fn->fd1, fn->fd2, 1, fn->varid); 2997 } else { 2998 int closed; 2999 if (fn->type != REDIR_HERESTR && xpandredir(fn, redir)) 3000 continue; 3001 if (errflag) { 3002 closemnodes(mfds); 3003 fixfds(save); 3004 execerr(); 3005 } 3006 if (isset(RESTRICTED) && IS_WRITE_FILE(fn->type)) { 3007 zwarn("writing redirection not allowed in restricted mode"); 3008 execerr(); 3009 } 3010 if (unset(EXECOPT)) 3011 continue; 3012 switch(fn->type) { 3013 case REDIR_HERESTR: 3014 if (!checkclobberparam(fn)) 3015 fil = -1; 3016 else 3017 fil = getherestr(fn); 3018 if (fil == -1) { 3019 if (errno && errno != EINTR) 3020 zwarn("can't create temp file for here document: %e", 3021 errno); 3022 closemnodes(mfds); 3023 fixfds(save); 3024 execerr(); 3025 } 3026 addfd(forked, save, mfds, fn->fd1, fil, 0, fn->varid); 3027 break; 3028 case REDIR_READ: 3029 case REDIR_READWRITE: 3030 if (!checkclobberparam(fn)) 3031 fil = -1; 3032 else if (fn->type == REDIR_READ) 3033 fil = open(unmeta(fn->name), O_RDONLY | O_NOCTTY); 3034 else 3035 fil = open(unmeta(fn->name), 3036 O_RDWR | O_CREAT | O_NOCTTY, 0666); 3037 if (fil == -1) { 3038 closemnodes(mfds); 3039 fixfds(save); 3040 if (errno != EINTR) 3041 zwarn("%e: %s", errno, fn->name); 3042 execerr(); 3043 } 3044 addfd(forked, save, mfds, fn->fd1, fil, 0, fn->varid); 3045 /* If this is 'exec < file', read from stdin, * 3046 * not terminal, unless `file' is a terminal. */ 3047 if (nullexec == 1 && fn->fd1 == 0 && 3048 isset(SHINSTDIN) && interact && !zleactive) 3049 init_io(); 3050 break; 3051 case REDIR_CLOSE: 3052 if (fn->varid) { 3053 char *s = fn->varid; 3054 struct value vbuf; 3055 Value v; 3056 int bad = 0; 3057 3058 if (!(v = getvalue(&vbuf, &s, 0))) { 3059 bad = 1; 3060 } else if (v->pm->node.flags & PM_READONLY) { 3061 bad = 2; 3062 } else { 3063 fn->fd1 = (int)getintvalue(v); 3064 if (errflag) 3065 bad = 1; 3066 else if (fn->fd1 <= max_zsh_fd) { 3067 if (fn->fd1 >= 10 && 3068 fdtable[fn->fd1] == FDT_INTERNAL) 3069 bad = 3; 3070 } 3071 } 3072 if (bad) { 3073 const char *bad_msg[] = { 3074 "parameter %s does not contain a file descriptor", 3075 "can't close file descriptor from readonly parameter %s", 3076 "file descriptor %d used by shell, not closed" 3077 }; 3078 if (bad > 2) 3079 zwarn(bad_msg[bad-1], fn->fd1); 3080 else 3081 zwarn(bad_msg[bad-1], fn->varid); 3082 execerr(); 3083 } 3084 } 3085 /* 3086 * Note we may attempt to close an fd beyond max_zsh_fd: 3087 * OK as long as we never look in fdtable for it. 3088 */ 3089 closed = 0; 3090 if (!forked && fn->fd1 < 10 && save[fn->fd1] == -2) { 3091 save[fn->fd1] = movefd(fn->fd1); 3092 if (save[fn->fd1] >= 0) { 3093 /* 3094 * The original fd is now closed, we don't need 3095 * to do it below. 3096 */ 3097 closed = 1; 3098 } 3099 } 3100 if (fn->fd1 < 10) 3101 closemn(mfds, fn->fd1, REDIR_CLOSE); 3102 if (!closed && zclose(fn->fd1) < 0) { 3103 zwarn("failed to close file descriptor %d: %e", 3104 fn->fd1, errno); 3105 } 3106 break; 3107 case REDIR_MERGEIN: 3108 case REDIR_MERGEOUT: 3109 if (fn->fd2 < 10) 3110 closemn(mfds, fn->fd2, fn->type); 3111 if (!checkclobberparam(fn)) 3112 fil = -1; 3113 else if (fn->fd2 > 9 && 3114 /* 3115 * If the requested fd is > max_zsh_fd, 3116 * the shell doesn't know about it. 3117 * Just assume the user knows what they're 3118 * doing. 3119 */ 3120 (fn->fd2 <= max_zsh_fd && 3121 ((fdtable[fn->fd2] != FDT_UNUSED && 3122 fdtable[fn->fd2] != FDT_EXTERNAL) || 3123 fn->fd2 == coprocin || 3124 fn->fd2 == coprocout))) { 3125 fil = -1; 3126 errno = EBADF; 3127 } else { 3128 int fd = fn->fd2; 3129 if(fd == -2) 3130 fd = (fn->type == REDIR_MERGEOUT) ? coprocout : coprocin; 3131 fil = movefd(dup(fd)); 3132 } 3133 if (fil == -1) { 3134 char fdstr[4]; 3135 3136 closemnodes(mfds); 3137 fixfds(save); 3138 if (fn->fd2 != -2) 3139 sprintf(fdstr, "%d", fn->fd2); 3140 if (errno) 3141 zwarn("%s: %e", fn->fd2 == -2 ? "coprocess" : fdstr, 3142 errno); 3143 execerr(); 3144 } 3145 addfd(forked, save, mfds, fn->fd1, fil, 3146 fn->type == REDIR_MERGEOUT, fn->varid); 3147 break; 3148 default: 3149 if (!checkclobberparam(fn)) 3150 fil = -1; 3151 else if (IS_APPEND_REDIR(fn->type)) 3152 fil = open(unmeta(fn->name), 3153 (unset(CLOBBER) && !IS_CLOBBER_REDIR(fn->type)) ? 3154 O_WRONLY | O_APPEND | O_NOCTTY : 3155 O_WRONLY | O_APPEND | O_CREAT | O_NOCTTY, 0666); 3156 else 3157 fil = clobber_open(fn); 3158 if(fil != -1 && IS_ERROR_REDIR(fn->type)) 3159 dfil = movefd(dup(fil)); 3160 else 3161 dfil = 0; 3162 if (fil == -1 || dfil == -1) { 3163 if(fil != -1) 3164 close(fil); 3165 closemnodes(mfds); 3166 fixfds(save); 3167 if (errno && errno != EINTR) 3168 zwarn("%e: %s", errno, fn->name); 3169 execerr(); 3170 } 3171 addfd(forked, save, mfds, fn->fd1, fil, 1, fn->varid); 3172 if(IS_ERROR_REDIR(fn->type)) 3173 addfd(forked, save, mfds, 2, dfil, 1, NULL); 3174 break; 3175 } 3176 /* May be error in addfd due to setting parameter. */ 3177 if (errflag) { 3178 closemnodes(mfds); 3179 fixfds(save); 3180 execerr(); 3181 } 3182 } 3183 } 3184 3185 /* We are done with redirection. close the mnodes, * 3186 * spawning tee/cat processes as necessary. */ 3187 for (i = 0; i < 10; i++) 3188 if (mfds[i] && mfds[i]->ct >= 2) 3189 closemn(mfds, i, REDIR_CLOSE); 3190 3191 if (nullexec) { 3192 if (nullexec == 1) { 3193 /* 3194 * If nullexec is 1 we specifically *don't* restore the original 3195 * fd's before returning. 3196 */ 3197 for (i = 0; i < 10; i++) 3198 if (save[i] != -2) 3199 zclose(save[i]); 3200 goto done; 3201 } 3202 /* 3203 * If nullexec is 2, we have variables to add with the redirections 3204 * in place. 3205 */ 3206 if (varspc) 3207 addvars(state, varspc, 0); 3208 lastval = errflag ? errflag : cmdoutval; 3209 if (isset(XTRACE)) { 3210 fputc('\n', xtrerr); 3211 fflush(xtrerr); 3212 } 3213 } else if (isset(EXECOPT) && !errflag) { 3214 /* 3215 * We delay the entersubsh() to here when we are exec'ing 3216 * the current shell (including a fake exec to run a builtin then 3217 * exit) in case there is an error return. 3218 */ 3219 if (is_exec) { 3220 int flags = ((how & Z_ASYNC) ? ESUB_ASYNC : 0) | 3221 ESUB_PGRP | ESUB_FAKE; 3222 if (type != WC_SUBSH) 3223 flags |= ESUB_KEEPTRAP; 3224 if ((do_exec || (type >= WC_CURSH && last1 == 1)) 3225 && !forked) 3226 flags |= ESUB_REVERTPGRP; 3227 entersubsh(flags); 3228 } 3229 if (type >= WC_CURSH) { 3230 if (last1 == 1) 3231 do_exec = 1; 3232 lastval = (execfuncs[type - WC_CURSH])(state, do_exec); 3233 } else if (is_builtin || is_shfunc) { 3234 LinkList restorelist = 0, removelist = 0; 3235 /* builtin or shell function */ 3236 3237 if (!forked && ((cflags & BINF_COMMAND) || 3238 (unset(POSIXBUILTINS) && !assign) || 3239 (isset(POSIXBUILTINS) && !is_shfunc && 3240 !(hn->flags & BINF_PSPECIAL)))) { 3241 if (varspc) 3242 save_params(state, varspc, &restorelist, &removelist); 3243 else 3244 restorelist = removelist = NULL; 3245 } 3246 if (varspc) { 3247 /* Export this if the command is a shell function, 3248 * but not if it's a builtin. 3249 */ 3250 int flags = 0; 3251 if (is_shfunc) 3252 flags |= ADDVAR_EXPORT; 3253 if (restorelist) 3254 flags |= ADDVAR_RESTORE; 3255 3256 addvars(state, varspc, flags); 3257 if (errflag) { 3258 if (restorelist) 3259 restore_params(restorelist, removelist); 3260 lastval = 1; 3261 fixfds(save); 3262 goto done; 3263 } 3264 } 3265 3266 if (is_shfunc) { 3267 /* It's a shell function */ 3268 pipecleanfilelist(filelist); 3269 execshfunc((Shfunc) hn, args); 3270 } else { 3271 /* It's a builtin */ 3272 if (forked) 3273 closem(FDT_INTERNAL); 3274 lastval = execbuiltin(args, (Builtin) hn); 3275 fflush(stdout); 3276 if (save[1] == -2) { 3277 if (ferror(stdout)) { 3278 zwarn("write error: %e", errno); 3279 clearerr(stdout); 3280 } 3281 } else 3282 clearerr(stdout); 3283 } 3284 if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) && 3285 lastval && !subsh) { 3286#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) 3287 fprintf(stderr, "zsh: exit %lld\n", lastval); 3288#else 3289 fprintf(stderr, "zsh: exit %ld\n", (long)lastval); 3290#endif 3291 fflush(stderr); 3292 } 3293 3294 if (do_exec) { 3295 if (subsh) 3296 _exit(lastval); 3297 3298 /* If we are exec'ing a command, and we are not in a subshell, * 3299 * then check if we should save the history file. */ 3300 if (isset(RCS) && interact && !nohistsave) 3301 savehistfile(NULL, 1, HFILE_USE_OPTIONS); 3302 exit(lastval); 3303 } 3304 if (restorelist) 3305 restore_params(restorelist, removelist); 3306 3307 } else { 3308 if (!forked) 3309 setiparam("SHLVL", --shlvl); 3310 if (do_exec) { 3311 /* If we are exec'ing a command, and we are not * 3312 * in a subshell, then save the history file. */ 3313 if (!subsh && isset(RCS) && interact && !nohistsave) 3314 savehistfile(NULL, 1, HFILE_USE_OPTIONS); 3315 } 3316 if (type == WC_SIMPLE) { 3317 if (varspc) { 3318 int addflags = ADDVAR_EXPORT|ADDVAR_RESTRICT; 3319 if (forked) 3320 addflags |= ADDVAR_RESTORE; 3321 addvars(state, varspc, addflags); 3322 if (errflag) 3323 _exit(1); 3324 } 3325 closem(FDT_INTERNAL); 3326 if (coprocin != -1) { 3327 zclose(coprocin); 3328 coprocin = -1; 3329 } 3330 if (coprocout != -1) { 3331 zclose(coprocout); 3332 coprocout = -1; 3333 } 3334#ifdef HAVE_GETRLIMIT 3335 if (!forked) 3336 setlimits(NULL); 3337#endif 3338 if (how & Z_ASYNC) { 3339 zsfree(STTYval); 3340 STTYval = 0; 3341 } 3342 execute(args, cflags, use_defpath); 3343 } else { /* ( ... ) */ 3344 DPUTS(varspc, 3345 "BUG: assignment before complex command"); 3346 list_pipe = 0; 3347 pipecleanfilelist(filelist); 3348 /* If we're forked (and we should be), no need to return */ 3349 DPUTS(last1 != 1 && !forked, "BUG: not exiting?"); 3350 DPUTS(type != WC_SUBSH, "Not sure what we're doing."); 3351 /* Skip word only used for try/always blocks */ 3352 state->pc++; 3353 execlist(state, 0, 1); 3354 } 3355 } 3356 } 3357 3358 err: 3359 if (forked) { 3360 /* 3361 * So what's going on here then? Well, I'm glad you asked. 3362 * 3363 * If we create multios for use in a subshell we do 3364 * this after forking, in this function above. That 3365 * means that the current (sub)process is responsible 3366 * for clearing them up. However, the processes won't 3367 * go away until we have closed the fd's talking to them. 3368 * Since we're about to exit the shell there's nothing 3369 * to stop us closing all fd's (including the ones 0 to 9 3370 * that we usually leave alone). 3371 * 3372 * Then we wait for any processes. When we forked, 3373 * we cleared the jobtable and started a new job just for 3374 * any oddments like this, so if there aren't any we won't 3375 * need to wait. The result of not waiting is that 3376 * the multios haven't flushed the fd's properly, leading 3377 * to obscure missing data. 3378 * 3379 * It would probably be cleaner to ensure that the 3380 * parent shell handled multios, but that requires 3381 * some architectural changes which are likely to be 3382 * hairy. 3383 */ 3384 for (i = 0; i < 10; i++) 3385 if (fdtable[i] != FDT_UNUSED) 3386 close(i); 3387 closem(FDT_UNUSED); 3388 if (thisjob != -1) 3389 waitjobs(); 3390 _exit(lastval); 3391 } 3392 fixfds(save); 3393 3394 done: 3395 if (isset(POSIXBUILTINS) && 3396 (cflags & (BINF_PSPECIAL|BINF_EXEC)) && 3397 !(orig_cflags & BINF_COMMAND)) { 3398 /* 3399 * For POSIX-compatible behaviour with special 3400 * builtins (including exec which we don't usually 3401 * classify as a builtin) we treat all errors as fatal. 3402 * The "command" builtin is not special so resets this behaviour. 3403 */ 3404 fatal: 3405 if (redir_err || errflag) { 3406 if (!isset(INTERACTIVE)) { 3407 if (forked) 3408 _exit(1); 3409 else 3410 exit(1); 3411 } 3412 errflag = 1; 3413 } 3414 } 3415 if (newxtrerr) { 3416 fil = fileno(newxtrerr); 3417 fclose(newxtrerr); 3418 xtrerr = oxtrerr; 3419 zclose(fil); 3420 } 3421 3422 zsfree(STTYval); 3423 STTYval = 0; 3424 if (oautocont >= 0) 3425 opts[AUTOCONTINUE] = oautocont; 3426} 3427 3428/* Arrange to have variables restored. */ 3429 3430/**/ 3431static void 3432save_params(Estate state, Wordcode pc, LinkList *restore_p, LinkList *remove_p) 3433{ 3434 Param pm; 3435 char *s; 3436 wordcode ac; 3437 3438 *restore_p = newlinklist(); 3439 *remove_p = newlinklist(); 3440 3441 while (wc_code(ac = *pc) == WC_ASSIGN) { 3442 s = ecrawstr(state->prog, pc + 1, NULL); 3443 if ((pm = (Param) paramtab->getnode(paramtab, s))) { 3444 Param tpm; 3445 if (pm->env) 3446 delenv(pm); 3447 if (!(pm->node.flags & PM_SPECIAL)) { 3448 /* 3449 * We used to remove ordinary parameters from the 3450 * table, but that meant "HELLO=$HELLO shellfunc" 3451 * failed because the expansion of $HELLO hasn't 3452 * been done at this point. Instead, copy the 3453 * parameter: in this case, we'll insert the 3454 * copied parameter straight back into the parameter 3455 * table so we want to be sure everything is 3456 * properly set up and in permanent memory. 3457 */ 3458 tpm = (Param) zshcalloc(sizeof *tpm); 3459 tpm->node.nam = ztrdup(pm->node.nam); 3460 copyparam(tpm, pm, 0); 3461 pm = tpm; 3462 } else if (!(pm->node.flags & PM_READONLY) && 3463 (unset(RESTRICTED) || !(pm->node.flags & PM_RESTRICTED))) { 3464 /* 3465 * In this case we're just saving parts of 3466 * the parameter in a tempory, so use heap allocation 3467 * and don't bother copying every detail. 3468 */ 3469 tpm = (Param) hcalloc(sizeof *tpm); 3470 tpm->node.nam = pm->node.nam; 3471 copyparam(tpm, pm, 1); 3472 pm = tpm; 3473 } 3474 addlinknode(*remove_p, dupstring(s)); 3475 addlinknode(*restore_p, pm); 3476 } else 3477 addlinknode(*remove_p, dupstring(s)); 3478 3479 pc += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ? 3480 3 : WC_ASSIGN_NUM(ac) + 2); 3481 } 3482} 3483 3484/* Restore saved parameters after executing a shfunc or builtin */ 3485 3486/**/ 3487static void 3488restore_params(LinkList restorelist, LinkList removelist) 3489{ 3490 Param pm; 3491 char *s; 3492 3493 /* remove temporary parameters */ 3494 while ((s = (char *) ugetnode(removelist))) { 3495 if ((pm = (Param) paramtab->getnode(paramtab, s)) && 3496 !(pm->node.flags & PM_SPECIAL)) { 3497 pm->node.flags &= ~PM_READONLY; 3498 unsetparam_pm(pm, 0, 0); 3499 } 3500 } 3501 3502 if (restorelist) { 3503 /* restore saved parameters */ 3504 while ((pm = (Param) ugetnode(restorelist))) { 3505 if (pm->node.flags & PM_SPECIAL) { 3506 Param tpm = (Param) paramtab->getnode(paramtab, pm->node.nam); 3507 3508 DPUTS(!tpm || PM_TYPE(pm->node.flags) != PM_TYPE(tpm->node.flags) || 3509 !(pm->node.flags & PM_SPECIAL), 3510 "BUG: in restoring special parameters"); 3511 if (!pm->env && tpm->env) 3512 delenv(tpm); 3513 tpm->node.flags = pm->node.flags; 3514 switch (PM_TYPE(pm->node.flags)) { 3515 case PM_SCALAR: 3516 tpm->gsu.s->setfn(tpm, pm->u.str); 3517 break; 3518 case PM_INTEGER: 3519 tpm->gsu.i->setfn(tpm, pm->u.val); 3520 break; 3521 case PM_EFLOAT: 3522 case PM_FFLOAT: 3523 tpm->gsu.f->setfn(tpm, pm->u.dval); 3524 break; 3525 case PM_ARRAY: 3526 tpm->gsu.a->setfn(tpm, pm->u.arr); 3527 break; 3528 case PM_HASHED: 3529 tpm->gsu.h->setfn(tpm, pm->u.hash); 3530 break; 3531 } 3532 pm = tpm; 3533 } else { 3534 paramtab->addnode(paramtab, pm->node.nam, pm); 3535 } 3536 if ((pm->node.flags & PM_EXPORTED) && ((s = getsparam(pm->node.nam)))) 3537 addenv(pm, s); 3538 } 3539 } 3540} 3541 3542/* restore fds after redirecting a builtin */ 3543 3544/**/ 3545static void 3546fixfds(int *save) 3547{ 3548 int old_errno = errno; 3549 int i; 3550 3551 for (i = 0; i != 10; i++) 3552 if (save[i] != -2) 3553 redup(save[i], i); 3554 errno = old_errno; 3555} 3556 3557/* 3558 * Close internal shell fds. 3559 * 3560 * Close any that are marked as used if "how" is FDT_UNUSED, else 3561 * close any with the value "how". 3562 */ 3563 3564/**/ 3565mod_export void 3566closem(int how) 3567{ 3568 int i; 3569 3570 for (i = 10; i <= max_zsh_fd; i++) 3571 if (fdtable[i] != FDT_UNUSED && 3572 (how == FDT_UNUSED || fdtable[i] == how)) 3573 zclose(i); 3574} 3575 3576/* convert here document into a here string */ 3577 3578/**/ 3579char * 3580gethere(char **strp, int typ) 3581{ 3582 char *buf; 3583 int bsiz, qt = 0, strip = 0; 3584 char *s, *t, *bptr, c; 3585 char *str = *strp; 3586 3587 for (s = str; *s; s++) 3588 if (inull(*s)) { 3589 qt = 1; 3590 break; 3591 } 3592 str = quotesubst(str); 3593 untokenize(str); 3594 if (typ == REDIR_HEREDOCDASH) { 3595 strip = 1; 3596 while (*str == '\t') 3597 str++; 3598 } 3599 *strp = str; 3600 bptr = buf = zalloc(bsiz = 256); 3601 for (;;) { 3602 t = bptr; 3603 3604 while ((c = hgetc()) == '\t' && strip) 3605 ; 3606 for (;;) { 3607 if (bptr == buf + bsiz) { 3608 char *newbuf = realloc(buf, 2 * bsiz); 3609 if (!newbuf) { 3610 /* out of memory */ 3611 zfree(buf, bsiz); 3612 return NULL; 3613 } 3614 buf = newbuf; 3615 t = buf + bsiz - (bptr - t); 3616 bptr = buf + bsiz; 3617 bsiz *= 2; 3618 } 3619 if (lexstop || c == '\n') 3620 break; 3621 *bptr++ = c; 3622 c = hgetc(); 3623 } 3624 *bptr = '\0'; 3625 if (!strcmp(t, str)) 3626 break; 3627 if (lexstop) { 3628 t = bptr; 3629 break; 3630 } 3631 *bptr++ = '\n'; 3632 } 3633 *t = '\0'; 3634 if (!qt) { 3635 int ef = errflag; 3636 3637 parsestr(buf); 3638 3639 if (!errflag) 3640 errflag = ef; 3641 } 3642 s = dupstring(buf); 3643 zfree(buf, bsiz); 3644 return s; 3645} 3646 3647/* open here string fd */ 3648 3649/**/ 3650static int 3651getherestr(struct redir *fn) 3652{ 3653 char *s, *t; 3654 int fd, len; 3655 3656 t = fn->name; 3657 singsub(&t); 3658 untokenize(t); 3659 unmetafy(t, &len); 3660 /* 3661 * For real here-strings we append a newline, as if the 3662 * string given was a complete command line. 3663 * 3664 * For here-strings from here documents, we use the original 3665 * text exactly. 3666 */ 3667 if (!(fn->flags & REDIRF_FROM_HEREDOC)) 3668 t[len++] = '\n'; 3669 if ((fd = gettempfile(NULL, 1, &s)) < 0) 3670 return -1; 3671 write_loop(fd, t, len); 3672 close(fd); 3673 fd = open(s, O_RDONLY | O_NOCTTY); 3674 unlink(s); 3675 return fd; 3676} 3677 3678/* 3679 * Test if some wordcode starts with a simple redirection of type 3680 * redir_type. If it does, return the name of the file, copied onto 3681 * the heap. If it doesn't, return NULL. 3682 */ 3683 3684static char * 3685simple_redir_name(Eprog prog, int redir_type) 3686{ 3687 Wordcode pc; 3688 3689 pc = prog->prog; 3690 if (prog != &dummy_eprog && 3691 wc_code(pc[0]) == WC_LIST && (WC_LIST_TYPE(pc[0]) & Z_END) && 3692 wc_code(pc[1]) == WC_SUBLIST && !WC_SUBLIST_FLAGS(pc[1]) && 3693 WC_SUBLIST_TYPE(pc[1]) == WC_SUBLIST_END && 3694 wc_code(pc[2]) == WC_PIPE && WC_PIPE_TYPE(pc[2]) == WC_PIPE_END && 3695 wc_code(pc[3]) == WC_REDIR && WC_REDIR_TYPE(pc[3]) == redir_type && 3696 !WC_REDIR_VARID(pc[3]) && 3697 !pc[4] && 3698 wc_code(pc[6]) == WC_SIMPLE && !WC_SIMPLE_ARGC(pc[6])) { 3699 return dupstring(ecrawstr(prog, pc + 5, NULL)); 3700 } 3701 3702 return NULL; 3703} 3704 3705/* $(...) */ 3706 3707/**/ 3708LinkList 3709getoutput(char *cmd, int qt) 3710{ 3711 Eprog prog; 3712 int pipes[2]; 3713 pid_t pid; 3714 char *s; 3715 3716 if (!(prog = parse_string(cmd, 0))) 3717 return NULL; 3718 3719 if ((s = simple_redir_name(prog, REDIR_READ))) { 3720 /* $(< word) */ 3721 int stream; 3722 3723 singsub(&s); 3724 if (errflag) 3725 return NULL; 3726 untokenize(s); 3727 if ((stream = open(unmeta(s), O_RDONLY | O_NOCTTY)) == -1) { 3728 zerr("%e: %s", errno, s); 3729 return NULL; 3730 } 3731 return readoutput(stream, qt); 3732 } 3733 if (mpipe(pipes) < 0) { 3734 errflag = 1; 3735 cmdoutpid = 0; 3736 return NULL; 3737 } 3738 child_block(); 3739 cmdoutval = 0; 3740 if ((cmdoutpid = pid = zfork(NULL)) == -1) { 3741 /* fork error */ 3742 zclose(pipes[0]); 3743 zclose(pipes[1]); 3744 errflag = 1; 3745 cmdoutpid = 0; 3746 child_unblock(); 3747 return NULL; 3748 } else if (pid) { 3749 LinkList retval; 3750 3751 zclose(pipes[1]); 3752 retval = readoutput(pipes[0], qt); 3753 fdtable[pipes[0]] = FDT_UNUSED; 3754 waitforpid(pid, 0); /* unblocks */ 3755 lastval = cmdoutval; 3756 return retval; 3757 } 3758 /* pid == 0 */ 3759 child_unblock(); 3760 zclose(pipes[0]); 3761 redup(pipes[1], 1); 3762 entersubsh(ESUB_PGRP|ESUB_NOMONITOR); 3763 cmdpush(CS_CMDSUBST); 3764 execode(prog, 0, 1, "cmdsubst"); 3765 cmdpop(); 3766 close(1); 3767 _exit(lastval); 3768 zerr("exit returned in child!!"); 3769 kill(getpid(), SIGKILL); 3770 return NULL; 3771} 3772 3773/* read output of command substitution */ 3774 3775/**/ 3776mod_export LinkList 3777readoutput(int in, int qt) 3778{ 3779 LinkList ret; 3780 char *buf, *ptr; 3781 int bsiz, c, cnt = 0; 3782 FILE *fin; 3783 3784 fin = fdopen(in, "r"); 3785 ret = newlinklist(); 3786 ptr = buf = (char *) hcalloc(bsiz = 64); 3787 while ((c = fgetc(fin)) != EOF || errno == EINTR) { 3788 if (c == EOF) { 3789 errno = 0; 3790 clearerr(fin); 3791 continue; 3792 } 3793 if (imeta(c)) { 3794 *ptr++ = Meta; 3795 c ^= 32; 3796 cnt++; 3797 } 3798 if (++cnt >= bsiz) { 3799 char *pp = (char *) hcalloc(bsiz *= 2); 3800 3801 memcpy(pp, buf, cnt - 1); 3802 ptr = (buf = pp) + cnt - 1; 3803 } 3804 *ptr++ = c; 3805 } 3806 fclose(fin); 3807 while (cnt && ptr[-1] == '\n') 3808 ptr--, cnt--; 3809 *ptr = '\0'; 3810 if (qt) { 3811 if (!cnt) { 3812 *ptr++ = Nularg; 3813 *ptr = '\0'; 3814 } 3815 addlinknode(ret, buf); 3816 } else { 3817 char **words = spacesplit(buf, 0, 1, 0); 3818 3819 while (*words) { 3820 if (isset(GLOBSUBST)) 3821 shtokenize(*words); 3822 addlinknode(ret, *words++); 3823 } 3824 } 3825 return ret; 3826} 3827 3828/**/ 3829static Eprog 3830parsecmd(char *cmd, char **eptr) 3831{ 3832 char *str; 3833 Eprog prog; 3834 3835 for (str = cmd + 2; *str && *str != Outpar; str++); 3836 if (!*str || cmd[1] != Inpar) { 3837 /* 3838 * This can happen if the expression is being parsed 3839 * inside another construct, e.g. as a value within ${..:..} etc. 3840 * So print a proper error message instead of the not very 3841 * useful but traditional "oops". 3842 */ 3843 char *errstr = dupstrpfx(cmd, 2); 3844 untokenize(errstr); 3845 zerr("unterminated `%s...)'", errstr); 3846 return NULL; 3847 } 3848 *str = '\0'; 3849 if (eptr) 3850 *eptr = str+1; 3851 if (!(prog = parse_string(cmd + 2, 0))) { 3852 zerr("parse error in process substitution"); 3853 return NULL; 3854 } 3855 return prog; 3856} 3857 3858/* =(...) */ 3859 3860/**/ 3861char * 3862getoutputfile(char *cmd, char **eptr) 3863{ 3864 pid_t pid; 3865 char *nam; 3866 Eprog prog; 3867 int fd; 3868 char *s; 3869 3870 if (thisjob == -1) 3871 return NULL; 3872 if (!(prog = parsecmd(cmd, eptr))) 3873 return NULL; 3874 if (!(nam = gettempname(NULL, 0))) 3875 return NULL; 3876 3877 if ((s = simple_redir_name(prog, REDIR_HERESTR))) { 3878 /* 3879 * =(<<<stuff). Optimise a la $(<file). It's 3880 * effectively the reverse, converting a string into a file name 3881 * rather than vice versa. 3882 */ 3883 singsub(&s); 3884 if (errflag) 3885 s = NULL; 3886 else 3887 untokenize(s); 3888 } 3889 3890 addfilelist(nam, 0); 3891 3892 if (!s) 3893 child_block(); 3894 fd = open(nam, O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0600); 3895 3896 if (s) { 3897 /* optimised here-string */ 3898 int len; 3899 unmetafy(s, &len); 3900 write_loop(fd, s, len); 3901 close(fd); 3902 return nam; 3903 } 3904 3905 if (fd < 0 || (cmdoutpid = pid = zfork(NULL)) == -1) { 3906 /* fork or open error */ 3907 child_unblock(); 3908 return nam; 3909 } else if (pid) { 3910 int os; 3911 3912 close(fd); 3913 os = jobtab[thisjob].stat; 3914 waitforpid(pid, 0); 3915 cmdoutval = 0; 3916 jobtab[thisjob].stat = os; 3917 return nam; 3918 } 3919 3920 /* pid == 0 */ 3921 redup(fd, 1); 3922 entersubsh(ESUB_PGRP|ESUB_NOMONITOR); 3923 cmdpush(CS_CMDSUBST); 3924 execode(prog, 0, 1, "equalsubst"); 3925 cmdpop(); 3926 close(1); 3927 _exit(lastval); 3928 zerr("exit returned in child!!"); 3929 kill(getpid(), SIGKILL); 3930 return NULL; 3931} 3932 3933#if !defined(PATH_DEV_FD) && defined(HAVE_FIFOS) 3934/* get a temporary named pipe */ 3935 3936static char * 3937namedpipe(void) 3938{ 3939 char *tnam = gettempname(NULL, 1); 3940 3941# ifdef HAVE_MKFIFO 3942 if (mkfifo(tnam, 0600) < 0) 3943# else 3944 if (mknod(tnam, 0010600, 0) < 0) 3945# endif 3946 return NULL; 3947 return tnam; 3948} 3949#endif /* ! PATH_DEV_FD && HAVE_FIFOS */ 3950 3951/* <(...) or >(...) */ 3952 3953/**/ 3954char * 3955getproc(char *cmd, char **eptr) 3956{ 3957#if !defined(HAVE_FIFOS) && !defined(PATH_DEV_FD) 3958 zerr("doesn't look like your system supports FIFOs."); 3959 return NULL; 3960#else 3961 Eprog prog; 3962 int out = *cmd == Inang; 3963 char *pnam; 3964 pid_t pid; 3965 struct timeval bgtime; 3966 3967#ifndef PATH_DEV_FD 3968 int fd; 3969 3970 if (thisjob == -1) 3971 return NULL; 3972 if (!(pnam = namedpipe())) 3973 return NULL; 3974 if (!(prog = parsecmd(cmd, eptr))) 3975 return NULL; 3976 addfilelist(pnam, 0); 3977 3978 if ((pid = zfork(&bgtime))) { 3979 if (pid == -1) 3980 return NULL; 3981 if (!out) 3982 addproc(pid, NULL, 1, &bgtime); 3983 return pnam; 3984 } 3985 closem(FDT_UNUSED); 3986 fd = open(pnam, out ? O_WRONLY | O_NOCTTY : O_RDONLY | O_NOCTTY); 3987 if (fd == -1) { 3988 zerr("can't open %s: %e", pnam, errno); 3989 _exit(1); 3990 } 3991 entersubsh(ESUB_ASYNC|ESUB_PGRP); 3992 redup(fd, out); 3993#else /* PATH_DEV_FD */ 3994 int pipes[2], fd; 3995 3996 if (thisjob == -1) 3997 return NULL; 3998 pnam = hcalloc(strlen(PATH_DEV_FD) + 6); 3999 if (!(prog = parsecmd(cmd, eptr))) 4000 return NULL; 4001 if (mpipe(pipes) < 0) 4002 return NULL; 4003 if ((pid = zfork(&bgtime))) { 4004 sprintf(pnam, "%s/%d", PATH_DEV_FD, pipes[!out]); 4005 zclose(pipes[out]); 4006 if (pid == -1) 4007 { 4008 zclose(pipes[!out]); 4009 return NULL; 4010 } 4011 fd = pipes[!out]; 4012 fdtable[fd] = FDT_PROC_SUBST; 4013 addfilelist(NULL, fd); 4014 if (!out) 4015 { 4016 addproc(pid, NULL, 1, &bgtime); 4017 } 4018 return pnam; 4019 } 4020 entersubsh(ESUB_ASYNC|ESUB_PGRP); 4021 redup(pipes[out], out); 4022 closem(FDT_UNUSED); /* this closes pipes[!out] as well */ 4023#endif /* PATH_DEV_FD */ 4024 4025 cmdpush(CS_CMDSUBST); 4026 execode(prog, 0, 1, out ? "outsubst" : "insubst"); 4027 cmdpop(); 4028 zclose(out); 4029 _exit(lastval); 4030 return NULL; 4031#endif /* HAVE_FIFOS and PATH_DEV_FD not defined */ 4032} 4033 4034/* 4035 * > >(...) or < <(...) (does not use named pipes) 4036 * 4037 * If the second argument is 1, this is part of 4038 * an "exec < <(...)" or "exec > >(...)" and we shouldn't 4039 * wait for the job to finish before continuing. 4040 */ 4041 4042/**/ 4043static int 4044getpipe(char *cmd, int nullexec) 4045{ 4046 Eprog prog; 4047 int pipes[2], out = *cmd == Inang; 4048 pid_t pid; 4049 struct timeval bgtime; 4050 char *ends; 4051 4052 if (!(prog = parsecmd(cmd, &ends))) 4053 return -1; 4054 if (*ends) { 4055 zerr("invalid syntax for process substitution in redirection"); 4056 return -1; 4057 } 4058 if (mpipe(pipes) < 0) 4059 return -1; 4060 if ((pid = zfork(&bgtime))) { 4061 zclose(pipes[out]); 4062 if (pid == -1) { 4063 zclose(pipes[!out]); 4064 return -1; 4065 } 4066 if (!nullexec) 4067 addproc(pid, NULL, 1, &bgtime); 4068 return pipes[!out]; 4069 } 4070 entersubsh(ESUB_PGRP); 4071 redup(pipes[out], out); 4072 closem(FDT_UNUSED); /* this closes pipes[!out] as well */ 4073 cmdpush(CS_CMDSUBST); 4074 execode(prog, 0, 1, out ? "outsubst" : "insubst"); 4075 cmdpop(); 4076 _exit(lastval); 4077 return 0; 4078} 4079 4080/* open pipes with fds >= 10 */ 4081 4082/**/ 4083static int 4084mpipe(int *pp) 4085{ 4086 if (pipe(pp) < 0) { 4087 zerr("pipe failed: %e", errno); 4088 return -1; 4089 } 4090 pp[0] = movefd(pp[0]); 4091 pp[1] = movefd(pp[1]); 4092 return 0; 4093} 4094 4095/* 4096 * Do process substitution with redirection 4097 * 4098 * If the second argument is 1, this is part of 4099 * an "exec < <(...)" or "exec > >(...)" and we shouldn't 4100 * wait for the job to finish before continuing. 4101 * Likewise, we shouldn't wait if we are opening the file 4102 * descriptor using the {fd}>>(...) notation since it stays 4103 * valid for subsequent commands. 4104 */ 4105 4106/**/ 4107static void 4108spawnpipes(LinkList l, int nullexec) 4109{ 4110 LinkNode n; 4111 Redir f; 4112 char *str; 4113 4114 n = firstnode(l); 4115 for (; n; incnode(n)) { 4116 f = (Redir) getdata(n); 4117 if (f->type == REDIR_OUTPIPE || f->type == REDIR_INPIPE) { 4118 str = f->name; 4119 f->fd2 = getpipe(str, nullexec || f->varid); 4120 } 4121 } 4122} 4123 4124extern int tracingcond; 4125 4126/* evaluate a [[ ... ]] */ 4127 4128/**/ 4129static int 4130execcond(Estate state, UNUSED(int do_exec)) 4131{ 4132 int stat; 4133 4134 state->pc--; 4135 if (isset(XTRACE)) { 4136 printprompt4(); 4137 fprintf(xtrerr, "[["); 4138 tracingcond++; 4139 } 4140 cmdpush(CS_COND); 4141 stat = evalcond(state, NULL); 4142 /* 4143 * 2 indicates a syntax error. For compatibility, turn this 4144 * into a shell error. 4145 */ 4146 if (stat == 2) 4147 errflag = 1; 4148 cmdpop(); 4149 if (isset(XTRACE)) { 4150 fprintf(xtrerr, " ]]\n"); 4151 fflush(xtrerr); 4152 tracingcond--; 4153 } 4154 return stat; 4155} 4156 4157/* evaluate a ((...)) arithmetic command */ 4158 4159/**/ 4160static int 4161execarith(Estate state, UNUSED(int do_exec)) 4162{ 4163 char *e; 4164 mnumber val = zero_mnumber; 4165 int htok = 0; 4166 4167 if (isset(XTRACE)) { 4168 printprompt4(); 4169 fprintf(xtrerr, "(("); 4170 } 4171 cmdpush(CS_MATH); 4172 e = ecgetstr(state, EC_DUPTOK, &htok); 4173 if (htok) 4174 singsub(&e); 4175 if (isset(XTRACE)) 4176 fprintf(xtrerr, " %s", e); 4177 4178 val = matheval(e); 4179 4180 cmdpop(); 4181 4182 if (isset(XTRACE)) { 4183 fprintf(xtrerr, " ))\n"); 4184 fflush(xtrerr); 4185 } 4186 if (errflag) { 4187 errflag = 0; 4188 return 2; 4189 } 4190 /* should test for fabs(val.u.d) < epsilon? */ 4191 return (val.type == MN_INTEGER) ? val.u.l == 0 : val.u.d == 0.0; 4192} 4193 4194/* perform time ... command */ 4195 4196/**/ 4197static int 4198exectime(Estate state, UNUSED(int do_exec)) 4199{ 4200 int jb; 4201 4202 jb = thisjob; 4203 if (WC_TIMED_TYPE(state->pc[-1]) == WC_TIMED_EMPTY) { 4204 shelltime(); 4205 return 0; 4206 } 4207 execpline(state, *state->pc++, Z_TIMED|Z_SYNC, 0); 4208 thisjob = jb; 4209 return lastval; 4210} 4211 4212/* Define a shell function */ 4213 4214/**/ 4215static int 4216execfuncdef(Estate state, UNUSED(int do_exec)) 4217{ 4218 Shfunc shf; 4219 char *s = NULL; 4220 int signum, nprg, sbeg, nstrs, npats, len, plen, i, htok = 0, ret = 0; 4221 Wordcode beg = state->pc, end; 4222 Eprog prog; 4223 Patprog *pp; 4224 LinkList names; 4225 4226 end = beg + WC_FUNCDEF_SKIP(state->pc[-1]); 4227 names = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok); 4228 nprg = end - beg; 4229 sbeg = *state->pc++; 4230 nstrs = *state->pc++; 4231 npats = *state->pc++; 4232 4233 nprg = (end - state->pc); 4234 plen = nprg * sizeof(wordcode); 4235 len = plen + (npats * sizeof(Patprog)) + nstrs; 4236 4237 if (htok && names) 4238 execsubst(names); 4239 4240 while (!names || (s = (char *) ugetnode(names))) { 4241 if (!names) { 4242 prog = (Eprog) zhalloc(sizeof(*prog)); 4243 prog->nref = -1; /* on the heap */ 4244 } else { 4245 prog = (Eprog) zalloc(sizeof(*prog)); 4246 prog->nref = 1; /* allocated from permanent storage */ 4247 } 4248 prog->npats = npats; 4249 prog->len = len; 4250 if (state->prog->dump || !names) { 4251 if (!names) { 4252 prog->flags = EF_HEAP; 4253 prog->dump = NULL; 4254 prog->pats = pp = (Patprog *) zhalloc(npats * sizeof(Patprog)); 4255 } else { 4256 prog->flags = EF_MAP; 4257 incrdumpcount(state->prog->dump); 4258 prog->dump = state->prog->dump; 4259 prog->pats = pp = (Patprog *) zalloc(npats * sizeof(Patprog)); 4260 } 4261 prog->prog = state->pc; 4262 prog->strs = state->strs + sbeg; 4263 } else { 4264 prog->flags = EF_REAL; 4265 prog->pats = pp = (Patprog *) zalloc(len); 4266 prog->prog = (Wordcode) (prog->pats + npats); 4267 prog->strs = (char *) (prog->prog + nprg); 4268 prog->dump = NULL; 4269 memcpy(prog->prog, state->pc, plen); 4270 memcpy(prog->strs, state->strs + sbeg, nstrs); 4271 } 4272 for (i = npats; i--; pp++) 4273 *pp = dummy_patprog1; 4274 prog->shf = NULL; 4275 4276 shf = (Shfunc) zalloc(sizeof(*shf)); 4277 shf->funcdef = prog; 4278 shf->node.flags = 0; 4279 shf->filename = ztrdup(scriptfilename); 4280 shf->lineno = lineno; 4281 shfunc_set_sticky(shf); 4282 4283 if (!names) { 4284 /* 4285 * Anonymous function, execute immediately. 4286 * Function name is "(anon)", parameter list is empty. 4287 */ 4288 LinkList args; 4289 4290 state->pc = end; 4291 end += *state->pc++; 4292 args = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok); 4293 4294 if (htok && args) 4295 execsubst(args); 4296 4297 if (!args) 4298 args = newlinklist(); 4299 shf->node.nam = "(anon)"; 4300 pushnode(args, shf->node.nam); 4301 4302 execshfunc(shf, args); 4303 ret = lastval; 4304 4305 freeeprog(shf->funcdef); 4306 zsfree(shf->filename); 4307 zfree(shf, sizeof(*shf)); 4308 break; 4309 } else { 4310 /* is this shell function a signal trap? */ 4311 if (!strncmp(s, "TRAP", 4) && 4312 (signum = getsignum(s + 4)) != -1) { 4313 if (settrap(signum, NULL, ZSIG_FUNC)) { 4314 freeeprog(shf->funcdef); 4315 zfree(shf, sizeof(*shf)); 4316 state->pc = end; 4317 return 1; 4318 } 4319 4320 /* 4321 * Remove the old node explicitly in case it has 4322 * an alternative name 4323 */ 4324 removetrapnode(signum); 4325 } 4326 shfunctab->addnode(shfunctab, ztrdup(s), shf); 4327 } 4328 } 4329 state->pc = end; 4330 return ret; 4331} 4332 4333/* Duplicate a sticky emulation */ 4334 4335/**/ 4336 4337mod_export Emulation_options 4338sticky_emulation_dup(Emulation_options src, int useheap) 4339{ 4340 Emulation_options newsticky = useheap ? 4341 hcalloc(sizeof(*src)) : zshcalloc(sizeof(*src)); 4342 newsticky->emulation = src->emulation; 4343 if (src->n_on_opts) { 4344 size_t sz = src->n_on_opts * sizeof(*src->on_opts); 4345 newsticky->n_on_opts = src->n_on_opts; 4346 newsticky->on_opts = useheap ? zhalloc(sz) : zalloc(sz); 4347 memcpy(newsticky->on_opts, src->on_opts, sz); 4348 } 4349 if (src->n_off_opts) { 4350 size_t sz = src->n_off_opts * sizeof(*src->off_opts); 4351 newsticky->n_off_opts = src->n_off_opts; 4352 newsticky->off_opts = useheap ? zhalloc(sz) : zalloc(sz); 4353 memcpy(newsticky->off_opts, src->off_opts, sz); 4354 } 4355 4356 return newsticky; 4357} 4358 4359/* Set the sticky emulation attributes for a shell function */ 4360 4361/**/ 4362 4363mod_export void 4364shfunc_set_sticky(Shfunc shf) 4365{ 4366 if (sticky) 4367 shf->sticky = sticky_emulation_dup(sticky, 0); 4368 else 4369 shf->sticky = NULL; 4370} 4371 4372 4373/* Main entry point to execute a shell function. */ 4374 4375/**/ 4376static void 4377execshfunc(Shfunc shf, LinkList args) 4378{ 4379 LinkList last_file_list = NULL; 4380 unsigned char *ocs; 4381 int ocsp, osfc; 4382 4383 if (errflag) 4384 return; 4385 4386 /* thisjob may be invalid if we're called via execsimple: see execcursh */ 4387 if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job && 4388 !hasprocs(thisjob)) { 4389 /* Without this deletejob the process table * 4390 * would be filled by a recursive function. */ 4391 last_file_list = jobtab[thisjob].filelist; 4392 jobtab[thisjob].filelist = NULL; 4393 deletejob(jobtab + thisjob, 0); 4394 } 4395 4396 if (isset(XTRACE)) { 4397 LinkNode lptr; 4398 printprompt4(); 4399 if (args) 4400 for (lptr = firstnode(args); lptr; incnode(lptr)) { 4401 if (lptr != firstnode(args)) 4402 fputc(' ', xtrerr); 4403 quotedzputs((char *)getdata(lptr), xtrerr); 4404 } 4405 fputc('\n', xtrerr); 4406 fflush(xtrerr); 4407 } 4408 ocs = cmdstack; 4409 ocsp = cmdsp; 4410 cmdstack = (unsigned char *) zalloc(CMDSTACKSZ); 4411 cmdsp = 0; 4412 if ((osfc = sfcontext) == SFC_NONE) 4413 sfcontext = SFC_DIRECT; 4414 xtrerr = stderr; 4415 doshfunc(shf, args, 0); 4416 sfcontext = osfc; 4417 free(cmdstack); 4418 cmdstack = ocs; 4419 cmdsp = ocsp; 4420 4421 if (!list_pipe) 4422 deletefilelist(last_file_list, 0); 4423} 4424 4425/* Function to execute the special type of command that represents an * 4426 * autoloaded shell function. The command structure tells us which * 4427 * function it is. This function is actually called as part of the * 4428 * execution of the autoloaded function itself, so when the function * 4429 * has been autoloaded, its list is just run with no frills. */ 4430 4431/**/ 4432static int 4433execautofn(Estate state, UNUSED(int do_exec)) 4434{ 4435 Shfunc shf; 4436 char *oldscriptname, *oldscriptfilename; 4437 4438 if (!(shf = loadautofn(state->prog->shf, 1, 0))) 4439 return 1; 4440 4441 /* 4442 * Probably we didn't know the filename where this function was 4443 * defined yet. 4444 */ 4445 if (funcstack && !funcstack->filename) 4446 funcstack->filename = dupstring(shf->filename); 4447 4448 oldscriptname = scriptname; 4449 oldscriptfilename = scriptfilename; 4450 scriptname = scriptfilename = dupstring(shf->node.nam); 4451 execode(shf->funcdef, 1, 0, "loadautofunc"); 4452 scriptname = oldscriptname; 4453 scriptfilename = oldscriptfilename; 4454 4455 return lastval; 4456} 4457 4458/**/ 4459Shfunc 4460loadautofn(Shfunc shf, int fksh, int autol) 4461{ 4462 int noalias = noaliases, ksh = 1; 4463 Eprog prog; 4464 char *fname; 4465 4466 pushheap(); 4467 4468 noaliases = (shf->node.flags & PM_UNALIASED); 4469 prog = getfpfunc(shf->node.nam, &ksh, &fname); 4470 noaliases = noalias; 4471 4472 if (ksh == 1) { 4473 ksh = fksh; 4474 if (ksh == 1) 4475 ksh = (shf->node.flags & PM_KSHSTORED) ? 2 : 4476 (shf->node.flags & PM_ZSHSTORED) ? 0 : 1; 4477 } 4478 4479 if (prog == &dummy_eprog) { 4480 /* We're not actually in the function; decrement locallevel */ 4481 locallevel--; 4482 zwarn("%s: function definition file not found", shf->node.nam); 4483 locallevel++; 4484 popheap(); 4485 return NULL; 4486 } 4487 if (!prog) { 4488 zsfree(fname); 4489 popheap(); 4490 return NULL; 4491 } 4492 if (ksh == 2 || (ksh == 1 && isset(KSHAUTOLOAD))) { 4493 if (autol) { 4494 prog->flags |= EF_RUN; 4495 4496 freeeprog(shf->funcdef); 4497 if (prog->flags & EF_MAP) 4498 shf->funcdef = prog; 4499 else 4500 shf->funcdef = dupeprog(prog, 0); 4501 shf->node.flags &= ~PM_UNDEFINED; 4502 shf->filename = fname; 4503 } else { 4504 VARARR(char, n, strlen(shf->node.nam) + 1); 4505 strcpy(n, shf->node.nam); 4506 execode(prog, 1, 0, "evalautofunc"); 4507 shf = (Shfunc) shfunctab->getnode(shfunctab, n); 4508 if (!shf || (shf->node.flags & PM_UNDEFINED)) { 4509 /* We're not actually in the function; decrement locallevel */ 4510 locallevel--; 4511 zwarn("%s: function not defined by file", n); 4512 locallevel++; 4513 popheap(); 4514 zsfree(fname); 4515 return NULL; 4516 } 4517 } 4518 } else { 4519 freeeprog(shf->funcdef); 4520 if (prog->flags & EF_MAP) 4521 shf->funcdef = stripkshdef(prog, shf->node.nam); 4522 else 4523 shf->funcdef = dupeprog(stripkshdef(prog, shf->node.nam), 0); 4524 shf->node.flags &= ~PM_UNDEFINED; 4525 shf->filename = fname; 4526 } 4527 popheap(); 4528 4529 return shf; 4530} 4531 4532/* 4533 * Check if a sticky emulation differs from the current one. 4534 */ 4535 4536/**/ 4537 4538int sticky_emulation_differs(Emulation_options sticky2) 4539{ 4540 /* If no new sticky emulation, not a different emulation */ 4541 if (!sticky2) 4542 return 0; 4543 /* If no current sticky emulation, different */ 4544 if (!sticky) 4545 return 1; 4546 /* If basic emulation different, different */ 4547 if (sticky->emulation != sticky2->emulation) 4548 return 1; 4549 /* If differing numbers of options, different */ 4550 if (sticky->n_on_opts != sticky2->n_on_opts || 4551 sticky->n_off_opts != sticky2->n_off_opts) 4552 return 1; 4553 /* 4554 * We need to compare option arrays, if non-null. 4555 * We made parseopts() create the list of options in option 4556 * order to make this easy. 4557 */ 4558 /* If different options turned on, different */ 4559 if (sticky->n_on_opts && 4560 memcmp(sticky->on_opts, sticky2->on_opts, 4561 sticky->n_on_opts * sizeof(*sticky->on_opts)) != 0) 4562 return 1; 4563 /* If different options turned on, different */ 4564 if (sticky->n_off_opts && 4565 memcmp(sticky->off_opts, sticky2->off_opts, 4566 sticky->n_off_opts * sizeof(*sticky->off_opts)) != 0) 4567 return 1; 4568 return 0; 4569} 4570 4571/* 4572 * execute a shell function 4573 * 4574 * name is the name of the function 4575 * 4576 * prog is the code to execute 4577 * 4578 * doshargs, if set, are parameters to pass to the function, 4579 * in which the first element is the function name (even if 4580 * FUNCTIONARGZERO is set as this is handled inside this function). 4581 * 4582 * If noreturnval is nonzero, then reset the current return 4583 * value (lastval) to its value before the shell function 4584 * was executed. However, in any case return the status value 4585 * from the function (i.e. if noreturnval is not set, this 4586 * will be the same as lastval). 4587 */ 4588 4589/**/ 4590mod_export int 4591doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval) 4592{ 4593 char **pptab, **x, *oargv0; 4594 int oldzoptind, oldlastval, oldoptcind, oldnumpipestats, ret; 4595 int *oldpipestats = NULL; 4596 char saveopts[OPT_SIZE], *oldscriptname = scriptname; 4597 char *name = shfunc->node.nam; 4598 int flags = shfunc->node.flags, ooflags; 4599 char *fname = dupstring(name); 4600 int obreaks, saveemulation, restore_sticky; 4601 Eprog prog; 4602 struct funcstack fstack; 4603 static int oflags; 4604 Emulation_options save_sticky = NULL; 4605#ifdef MAX_FUNCTION_DEPTH 4606 static int funcdepth; 4607#endif 4608 4609 pushheap(); 4610 4611 oargv0 = NULL; 4612 obreaks = breaks;; 4613 if (trap_state == TRAP_STATE_PRIMED) 4614 trap_return--; 4615 oldlastval = lastval; 4616 oldnumpipestats = numpipestats; 4617 if (noreturnval) { 4618 /* 4619 * Easiest to use the heap here since we're bracketed 4620 * immediately by a pushheap/popheap pair. 4621 */ 4622 size_t bytes = sizeof(int)*numpipestats; 4623 oldpipestats = (int *)zhalloc(bytes); 4624 memcpy(oldpipestats, pipestats, bytes); 4625 } 4626 4627 starttrapscope(); 4628 startpatternscope(); 4629 4630 pptab = pparams; 4631 if (!(flags & PM_UNDEFINED)) 4632 scriptname = dupstring(name); 4633 oldzoptind = zoptind; 4634 zoptind = 1; 4635 oldoptcind = optcind; 4636 optcind = 0; 4637 4638 /* We need to save the current options even if LOCALOPTIONS is * 4639 * not currently set. That's because if it gets set in the * 4640 * function we need to restore the original options on exit. */ 4641 memcpy(saveopts, opts, sizeof(opts)); 4642 saveemulation = emulation; 4643 save_sticky = sticky; 4644 4645 if (sticky_emulation_differs(shfunc->sticky)) { 4646 /* 4647 * Function is marked for sticky emulation. 4648 * Enable it now. 4649 * 4650 * We deliberately do not do this if the sticky emulation 4651 * in effect is the same as that requested. This enables 4652 * option setting naturally within emulation environments. 4653 * Note that a difference in EMULATE_FULLY (emulate with 4654 * or without -R) counts as a different environment. 4655 * 4656 * This propagates the sticky emulation to subfunctions. 4657 */ 4658 sticky = sticky_emulation_dup(shfunc->sticky, 1); 4659 emulation = sticky->emulation; 4660 restore_sticky = 1; 4661 installemulation(emulation, opts); 4662 if (sticky->n_on_opts) { 4663 OptIndex *onptr; 4664 for (onptr = sticky->on_opts; 4665 onptr < sticky->on_opts + sticky->n_on_opts; 4666 onptr++) 4667 opts[*onptr] = 1; 4668 } 4669 if (sticky->n_off_opts) { 4670 OptIndex *offptr; 4671 for (offptr = sticky->off_opts; 4672 offptr < sticky->off_opts + sticky->n_off_opts; 4673 offptr++) 4674 opts[*offptr] = 0; 4675 } 4676 /* All emulations start with pattern disables clear */ 4677 clearpatterndisables(); 4678 } else 4679 restore_sticky = 0; 4680 4681 if (flags & (PM_TAGGED|PM_TAGGED_LOCAL)) 4682 opts[XTRACE] = 1; 4683 else if (oflags & PM_TAGGED_LOCAL) 4684 opts[XTRACE] = 0; 4685 ooflags = oflags; 4686 /* 4687 * oflags is static, because we compare it on the next recursive 4688 * call. Hence also we maintain ooflags for restoring the previous 4689 * value of oflags after the call. 4690 */ 4691 oflags = flags; 4692 opts[PRINTEXITVALUE] = 0; 4693 if (doshargs) { 4694 LinkNode node; 4695 4696 node = firstnode(doshargs); 4697 pparams = x = (char **) zshcalloc(((sizeof *x) * 4698 (1 + countlinknodes(doshargs)))); 4699 if (isset(FUNCTIONARGZERO)) { 4700 oargv0 = argzero; 4701 argzero = ztrdup(getdata(node)); 4702 } 4703 /* first node contains name regardless of option */ 4704 node = node->next; 4705 for (; node; node = node->next, x++) 4706 *x = ztrdup(getdata(node)); 4707 } else { 4708 pparams = (char **) zshcalloc(sizeof *pparams); 4709 if (isset(FUNCTIONARGZERO)) { 4710 oargv0 = argzero; 4711 argzero = ztrdup(argzero); 4712 } 4713 } 4714#ifdef MAX_FUNCTION_DEPTH 4715 if(++funcdepth > MAX_FUNCTION_DEPTH) 4716 { 4717 zerr("maximum nested function level reached"); 4718 goto undoshfunc; 4719 } 4720#endif 4721 fstack.name = dupstring(name); 4722 /* 4723 * The caller is whatever is immediately before on the stack, 4724 * unless we're at the top, in which case it's the script 4725 * or interactive shell name. 4726 */ 4727 fstack.caller = funcstack ? funcstack->name : 4728 dupstring(oargv0 ? oargv0 : argzero); 4729 fstack.lineno = lineno; 4730 fstack.prev = funcstack; 4731 fstack.tp = FS_FUNC; 4732 funcstack = &fstack; 4733 4734 fstack.flineno = shfunc->lineno; 4735 fstack.filename = dupstring(shfunc->filename); 4736 4737 prog = shfunc->funcdef; 4738 if (prog->flags & EF_RUN) { 4739 Shfunc shf; 4740 4741 prog->flags &= ~EF_RUN; 4742 4743 runshfunc(prog, NULL, fstack.name); 4744 4745 if (!(shf = (Shfunc) shfunctab->getnode(shfunctab, 4746 (name = fname)))) { 4747 zwarn("%s: function not defined by file", name); 4748 if (noreturnval) 4749 errflag = 1; 4750 else 4751 lastval = 1; 4752 goto doneshfunc; 4753 } 4754 prog = shf->funcdef; 4755 } 4756 runshfunc(prog, wrappers, fstack.name); 4757 doneshfunc: 4758 funcstack = fstack.prev; 4759#ifdef MAX_FUNCTION_DEPTH 4760 undoshfunc: 4761 --funcdepth; 4762#endif 4763 if (retflag) { 4764 retflag = 0; 4765 breaks = obreaks; 4766 } 4767 freearray(pparams); 4768 if (oargv0) { 4769 zsfree(argzero); 4770 argzero = oargv0; 4771 } 4772 pparams = pptab; 4773 optcind = oldoptcind; 4774 zoptind = oldzoptind; 4775 scriptname = oldscriptname; 4776 oflags = ooflags; 4777 4778 endpatternscope(); /* before restoring old LOCALPATTERNS */ 4779 4780 if (restore_sticky) { 4781 /* 4782 * If we switched to an emulation environment just for 4783 * this function, we interpret the option and emulation 4784 * switch as being a firewall between environments. 4785 */ 4786 memcpy(opts, saveopts, sizeof(opts)); 4787 emulation = saveemulation; 4788 sticky = save_sticky; 4789 } else if (isset(LOCALOPTIONS)) { 4790 /* restore all shell options except PRIVILEGED and RESTRICTED */ 4791 saveopts[PRIVILEGED] = opts[PRIVILEGED]; 4792 saveopts[RESTRICTED] = opts[RESTRICTED]; 4793 memcpy(opts, saveopts, sizeof(opts)); 4794 emulation = saveemulation; 4795 } else { 4796 /* just restore a couple. */ 4797 opts[XTRACE] = saveopts[XTRACE]; 4798 opts[PRINTEXITVALUE] = saveopts[PRINTEXITVALUE]; 4799 opts[LOCALOPTIONS] = saveopts[LOCALOPTIONS]; 4800 } 4801 4802 endtrapscope(); 4803 4804 if (trap_state == TRAP_STATE_PRIMED) 4805 trap_return++; 4806 ret = lastval; 4807 if (noreturnval) { 4808 lastval = oldlastval; 4809 numpipestats = oldnumpipestats; 4810 memcpy(pipestats, oldpipestats, sizeof(int)*numpipestats); 4811 } 4812 popheap(); 4813 4814 if (exit_pending) { 4815 if (locallevel > forklevel) { 4816 /* Still functions to return: force them to do so. */ 4817 retflag = 1; 4818 breaks = loops; 4819 } else { 4820 /* 4821 * All functions finished: time to exit the shell. 4822 * We already did the `stopmsg' test when the 4823 * exit command was handled. 4824 */ 4825 stopmsg = 1; 4826 zexit(exit_pending >> 1, 0); 4827 } 4828 } 4829 4830 return ret; 4831} 4832 4833/* This finally executes a shell function and any function wrappers * 4834 * defined by modules. This works by calling the wrapper function which * 4835 * in turn has to call back this function with the arguments it gets. */ 4836 4837/**/ 4838mod_export void 4839runshfunc(Eprog prog, FuncWrap wrap, char *name) 4840{ 4841 int cont, ouu; 4842 char *ou; 4843 4844 ou = zalloc(ouu = underscoreused); 4845 if (ou) 4846 memcpy(ou, zunderscore, underscoreused); 4847 4848 while (wrap) { 4849 wrap->module->wrapper++; 4850 cont = wrap->handler(prog, wrap->next, name); 4851 wrap->module->wrapper--; 4852 4853 if (!wrap->module->wrapper && 4854 (wrap->module->node.flags & MOD_UNLOAD)) 4855 unload_module(wrap->module); 4856 4857 if (!cont) { 4858 if (ou) 4859 zfree(ou, ouu); 4860 return; 4861 } 4862 wrap = wrap->next; 4863 } 4864 startparamscope(); 4865 execode(prog, 1, 0, "shfunc"); 4866 if (ou) { 4867 setunderscore(ou); 4868 zfree(ou, ouu); 4869 } 4870 endparamscope(); 4871} 4872 4873/* Search fpath for an undefined function. Finds the file, and returns the * 4874 * list of its contents. */ 4875 4876/**/ 4877Eprog 4878getfpfunc(char *s, int *ksh, char **fname) 4879{ 4880 char **pp, buf[PATH_MAX]; 4881 off_t len; 4882 off_t rlen; 4883 char *d; 4884 Eprog r; 4885 int fd; 4886 4887 pp = fpath; 4888 for (; *pp; pp++) { 4889 if (strlen(*pp) + strlen(s) + 1 >= PATH_MAX) 4890 continue; 4891 if (**pp) 4892 sprintf(buf, "%s/%s", *pp, s); 4893 else 4894 strcpy(buf, s); 4895 if ((r = try_dump_file(*pp, s, buf, ksh))) { 4896 if (fname) 4897 *fname = ztrdup(buf); 4898 return r; 4899 } 4900 unmetafy(buf, NULL); 4901 if (!access(buf, R_OK) && (fd = open(buf, O_RDONLY | O_NOCTTY)) != -1) { 4902 if ((len = lseek(fd, 0, 2)) != -1) { 4903 d = (char *) zalloc(len + 1); 4904 lseek(fd, 0, 0); 4905 if ((rlen = read(fd, d, len)) >= 0) { 4906 char *oldscriptname = scriptname; 4907 4908 close(fd); 4909 d[rlen] = '\0'; 4910 d = metafy(d, rlen, META_REALLOC); 4911 4912 scriptname = dupstring(s); 4913 r = parse_string(d, 1); 4914 scriptname = oldscriptname; 4915 4916 if (fname) 4917 *fname = ztrdup(buf); 4918 4919 zfree(d, len + 1); 4920 4921 return r; 4922 } else 4923 close(fd); 4924 4925 zfree(d, len + 1); 4926 } else 4927 close(fd); 4928 } 4929 } 4930 return &dummy_eprog; 4931} 4932 4933/* Handle the most common type of ksh-style autoloading, when doing a * 4934 * zsh-style autoload. Given the list read from an autoload file, and the * 4935 * name of the function being defined, check to see if the file consists * 4936 * entirely of a single definition for that function. If so, use the * 4937 * contents of that definition. Otherwise, use the entire file. */ 4938 4939/**/ 4940Eprog 4941stripkshdef(Eprog prog, char *name) 4942{ 4943 Wordcode pc; 4944 wordcode code; 4945 4946 if (!prog) 4947 return NULL; 4948 pc = prog->prog; 4949 code = *pc++; 4950 if (wc_code(code) != WC_LIST || 4951 (WC_LIST_TYPE(code) & (Z_SYNC|Z_END|Z_SIMPLE)) != (Z_SYNC|Z_END|Z_SIMPLE)) 4952 return prog; 4953 pc++; 4954 code = *pc++; 4955 if (wc_code(code) != WC_FUNCDEF || 4956 *pc != 1 || strcmp(name, ecrawstr(prog, pc + 1, NULL))) 4957 return prog; 4958 4959 { 4960 Eprog ret; 4961 Wordcode end = pc + WC_FUNCDEF_SKIP(code); 4962 int sbeg = pc[2], nstrs = pc[3], nprg, npats = pc[4], plen, len, i; 4963 Patprog *pp; 4964 4965 pc += 5; 4966 4967 nprg = end - pc; 4968 plen = nprg * sizeof(wordcode); 4969 len = plen + (npats * sizeof(Patprog)) + nstrs; 4970 4971 if (prog->flags & EF_MAP) { 4972 ret = prog; 4973 free(prog->pats); 4974 ret->pats = pp = (Patprog *) zalloc(npats * sizeof(Patprog)); 4975 ret->prog = pc; 4976 ret->strs = prog->strs + sbeg; 4977 } else { 4978 ret = (Eprog) zhalloc(sizeof(*ret)); 4979 ret->flags = EF_HEAP; 4980 ret->pats = pp = (Patprog *) zhalloc(len); 4981 ret->prog = (Wordcode) (ret->pats + npats); 4982 ret->strs = (char *) (ret->prog + nprg); 4983 memcpy(ret->prog, pc, plen); 4984 memcpy(ret->strs, prog->strs + sbeg, nstrs); 4985 ret->dump = NULL; 4986 } 4987 ret->len = len; 4988 ret->npats = npats; 4989 for (i = npats; i--; pp++) 4990 *pp = dummy_patprog1; 4991 ret->shf = NULL; 4992 4993 return ret; 4994 } 4995} 4996 4997/* check to see if AUTOCD applies here */ 4998 4999/**/ 5000static char * 5001cancd(char *s) 5002{ 5003 int nocdpath = s[0] == '.' && 5004 (s[1] == '/' || !s[1] || (s[1] == '.' && (s[2] == '/' || !s[1]))); 5005 char *t; 5006 5007 if (*s != '/') { 5008 char sbuf[PATH_MAX], **cp; 5009 5010 if (cancd2(s)) 5011 return s; 5012 if (access(unmeta(s), X_OK) == 0) 5013 return NULL; 5014 if (!nocdpath) 5015 for (cp = cdpath; *cp; cp++) { 5016 if (strlen(*cp) + strlen(s) + 1 >= PATH_MAX) 5017 continue; 5018 if (**cp) 5019 sprintf(sbuf, "%s/%s", *cp, s); 5020 else 5021 strcpy(sbuf, s); 5022 if (cancd2(sbuf)) { 5023 doprintdir = -1; 5024 return dupstring(sbuf); 5025 } 5026 } 5027 if ((t = cd_able_vars(s))) { 5028 if (cancd2(t)) { 5029 doprintdir = -1; 5030 return t; 5031 } 5032 } 5033 return NULL; 5034 } 5035 return cancd2(s) ? s : NULL; 5036} 5037 5038/**/ 5039static int 5040cancd2(char *s) 5041{ 5042 struct stat buf; 5043 char *us, *us2 = NULL; 5044 int ret; 5045 5046 /* 5047 * If CHASEDOTS and CHASELINKS are not set, we want to rationalize the 5048 * path by removing foo/.. combinations in the logical rather than 5049 * the physical path. If either is set, we test the physical path. 5050 */ 5051 if (!isset(CHASEDOTS) && !isset(CHASELINKS)) { 5052 if (*s != '/') 5053 us = tricat(pwd[1] ? pwd : "", "/", s); 5054 else 5055 us = ztrdup(s); 5056 fixdir(us2 = us); 5057 } else 5058 us = unmeta(s); 5059 ret = !(access(us, X_OK) || stat(us, &buf) || !S_ISDIR(buf.st_mode)); 5060 if (us2) 5061 free(us2); 5062 return ret; 5063} 5064 5065/**/ 5066void 5067execsave(void) 5068{ 5069 struct execstack *es; 5070 5071 es = (struct execstack *) malloc(sizeof(struct execstack)); 5072 es->list_pipe_pid = list_pipe_pid; 5073 es->nowait = nowait; 5074 es->pline_level = pline_level; 5075 es->list_pipe_child = list_pipe_child; 5076 es->list_pipe_job = list_pipe_job; 5077 strcpy(es->list_pipe_text, list_pipe_text); 5078 es->lastval = lastval; 5079 es->noeval = noeval; 5080 es->badcshglob = badcshglob; 5081 es->cmdoutpid = cmdoutpid; 5082 es->cmdoutval = cmdoutval; 5083 es->use_cmdoutval = use_cmdoutval; 5084 es->trap_return = trap_return; 5085 es->trap_state = trap_state; 5086 es->trapisfunc = trapisfunc; 5087 es->traplocallevel = traplocallevel; 5088 es->noerrs = noerrs; 5089 es->underscore = ztrdup(zunderscore); 5090 es->next = exstack; 5091 exstack = es; 5092 noerrs = cmdoutpid = 0; 5093} 5094 5095/**/ 5096void 5097execrestore(void) 5098{ 5099 struct execstack *en = exstack; 5100 5101 DPUTS(!exstack, "BUG: execrestore() without execsave()"); 5102 5103 queue_signals(); 5104 exstack = exstack->next; 5105 5106 list_pipe_pid = en->list_pipe_pid; 5107 nowait = en->nowait; 5108 pline_level = en->pline_level; 5109 list_pipe_child = en->list_pipe_child; 5110 list_pipe_job = en->list_pipe_job; 5111 strcpy(list_pipe_text, en->list_pipe_text); 5112 lastval = en->lastval; 5113 noeval = en->noeval; 5114 badcshglob = en->badcshglob; 5115 cmdoutpid = en->cmdoutpid; 5116 cmdoutval = en->cmdoutval; 5117 use_cmdoutval = en->use_cmdoutval; 5118 trap_return = en->trap_return; 5119 trap_state = en->trap_state; 5120 trapisfunc = en->trapisfunc; 5121 traplocallevel = en->traplocallevel; 5122 noerrs = en->noerrs; 5123 setunderscore(en->underscore); 5124 zsfree(en->underscore); 5125 free(en); 5126 5127 unqueue_signals(); 5128} 5129