Home | History | Annotate | Line # | Download | only in ksh
c_sh.c revision 1.14.2.1
      1 /*	$NetBSD: c_sh.c,v 1.14.2.1 2014/05/22 11:26:23 yamt Exp $	*/
      2 
      3 /*
      4  * built-in Bourne commands
      5  */
      6 #include <sys/cdefs.h>
      7 
      8 #ifndef lint
      9 __RCSID("$NetBSD: c_sh.c,v 1.14.2.1 2014/05/22 11:26:23 yamt Exp $");
     10 #endif
     11 
     12 
     13 #include "sh.h"
     14 #include "ksh_stat.h" 	/* umask() */
     15 #include "ksh_time.h"
     16 #include "ksh_times.h"
     17 
     18 static	char *clocktos ARGS((clock_t t));
     19 
     20 
     21 /* :, false and true */
     22 int
     23 c_label(wp)
     24 	char **wp;
     25 {
     26 	return wp[0][0] == 'f' ? 1 : 0;
     27 }
     28 
     29 int
     30 c_shift(wp)
     31 	char **wp;
     32 {
     33 	register struct block *l = e->loc;
     34 	register int n;
     35 	long val;
     36 	char *arg;
     37 
     38 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
     39 		return 1;
     40 	arg = wp[builtin_opt.optind];
     41 
     42 	if (arg) {
     43 		evaluate(arg, &val, KSH_UNWIND_ERROR);
     44 		n = val;
     45 	} else
     46 		n = 1;
     47 	if (n < 0) {
     48 		bi_errorf("%s: bad number", arg);
     49 		return (1);
     50 	}
     51 	if (l->argc < n) {
     52 		bi_errorf("nothing to shift");
     53 		return (1);
     54 	}
     55 	l->argv[n] = l->argv[0];
     56 	l->argv += n;
     57 	l->argc -= n;
     58 	return 0;
     59 }
     60 
     61 int
     62 c_umask(wp)
     63 	char **wp;
     64 {
     65 	register int i;
     66 	register char *cp;
     67 	int symbolic = 0;
     68 	int old_umask;
     69 	int optc;
     70 
     71 	while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != EOF)
     72 		switch (optc) {
     73 		  case 'S':
     74 			symbolic = 1;
     75 			break;
     76 		  case '?':
     77 			return 1;
     78 		}
     79 	cp = wp[builtin_opt.optind];
     80 	if (cp == NULL) {
     81 		old_umask = umask(0);
     82 		umask(old_umask);
     83 		if (symbolic) {
     84 			char buf[18];
     85 			int j;
     86 
     87 			old_umask = ~old_umask;
     88 			cp = buf;
     89 			for (i = 0; i < 3; i++) {
     90 				*cp++ = "ugo"[i];
     91 				*cp++ = '=';
     92 				for (j = 0; j < 3; j++)
     93 					if (old_umask & (1 << (8 - (3*i + j))))
     94 						*cp++ = "rwx"[j];
     95 				*cp++ = ',';
     96 			}
     97 			cp[-1] = '\0';
     98 			shprintf("%s\n", buf);
     99 		} else
    100 			shprintf("%#3.3o\n", old_umask);
    101 	} else {
    102 		int new_umask;
    103 
    104 		if (digit(*cp)) {
    105 			for (new_umask = 0; *cp >= '0' && *cp <= '7'; cp++)
    106 				new_umask = new_umask * 8 + (*cp - '0');
    107 			if (*cp) {
    108 				bi_errorf("bad number");
    109 				return 1;
    110 			}
    111 		} else {
    112 			/* symbolic format */
    113 			int positions, new_val;
    114 			char op;
    115 
    116 			old_umask = umask(0);
    117 			umask(old_umask); /* in case of error */
    118 			old_umask = ~old_umask;
    119 			new_umask = old_umask;
    120 			positions = 0;
    121 			while (*cp) {
    122 				while (*cp && strchr("augo", *cp))
    123 					switch (*cp++) {
    124 					case 'a': positions |= 0111; break;
    125 					case 'u': positions |= 0100; break;
    126 					case 'g': positions |= 0010; break;
    127 					case 'o': positions |= 0001; break;
    128 					}
    129 				if (!positions)
    130 					positions = 0111; /* default is a */
    131 				if (!strchr("=+-", op = *cp))
    132 					break;
    133 				cp++;
    134 				new_val = 0;
    135 				while (*cp && strchr("rwxugoXs", *cp))
    136 					switch (*cp++) {
    137 					case 'r': new_val |= 04; break;
    138 					case 'w': new_val |= 02; break;
    139 					case 'x': new_val |= 01; break;
    140 					case 'u': new_val |= old_umask >> 6;
    141 						  break;
    142 					case 'g': new_val |= old_umask >> 3;
    143 						  break;
    144 					case 'o': new_val |= old_umask >> 0;
    145 						  break;
    146 					case 'X': if (old_umask & 0111)
    147 							new_val |= 01;
    148 						  break;
    149 					case 's': /* ignored */
    150 						  break;
    151 					}
    152 				new_val = (new_val & 07) * positions;
    153 				switch (op) {
    154 				case '-':
    155 					new_umask &= ~new_val;
    156 					break;
    157 				case '=':
    158 					new_umask = new_val
    159 					    | (new_umask & ~(positions * 07));
    160 					break;
    161 				case '+':
    162 					new_umask |= new_val;
    163 				}
    164 				if (*cp == ',') {
    165 					positions = 0;
    166 					cp++;
    167 				} else if (!strchr("=+-", *cp))
    168 					break;
    169 			}
    170 			if (*cp) {
    171 				bi_errorf("bad mask");
    172 				return 1;
    173 			}
    174 			new_umask = ~new_umask;
    175 		}
    176 		umask(new_umask);
    177 	}
    178 	return 0;
    179 }
    180 
    181 int
    182 c_dot(wp)
    183 	char **wp;
    184 {
    185 	char *file, *cp;
    186 	char **argv;
    187 	int argc;
    188 	int i;
    189 	int err;
    190 
    191 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
    192 		return 1;
    193 
    194 	if ((cp = wp[builtin_opt.optind]) == NULL)
    195 		return 0;
    196 	file = search(cp, path, R_OK, &err);
    197 	if (file == NULL) {
    198 		bi_errorf("%s: %s", cp, err ? strerror(err) : "not found");
    199 		return 1;
    200 	}
    201 
    202 	/* Set positional parameters? */
    203 	if (wp[builtin_opt.optind + 1]) {
    204 		argv = wp + builtin_opt.optind;
    205 		argv[0] = e->loc->argv[0]; /* preserve $0 */
    206 		for (argc = 0; argv[argc + 1]; argc++)
    207 			;
    208 	} else {
    209 		argc = 0;
    210 		argv = (char **) 0;
    211 	}
    212 	i = include(file, argc, argv, 0);
    213 	if (i < 0) { /* should not happen */
    214 		bi_errorf("%s: %s", cp, strerror(errno));
    215 		return 1;
    216 	}
    217 	return i;
    218 }
    219 
    220 int
    221 c_wait(wp)
    222 	char **wp;
    223 {
    224 	int UNINITIALIZED(rv);
    225 	int sig;
    226 
    227 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
    228 		return 1;
    229 	wp += builtin_opt.optind;
    230 	if (*wp == (char *) 0) {
    231 		while (waitfor((char *) 0, &sig) >= 0)
    232 			;
    233 		rv = sig;
    234 	} else {
    235 		for (; *wp; wp++)
    236 			rv = waitfor(*wp, &sig);
    237 		if (rv < 0)
    238 			rv = sig ? sig : 127; /* magic exit code: bad job-id */
    239 	}
    240 	return rv;
    241 }
    242 
    243 int
    244 c_read(wp)
    245 	char **wp;
    246 {
    247 	register int c = 0;
    248 	int expandv = 1, history = 0;
    249 	int expanding;
    250 	int ecode = 0;
    251 	register char *cp;
    252 	int fd = 0;
    253 	struct shf *shf;
    254 	int optc;
    255 	const char *emsg;
    256 	XString cs, xs;
    257 	struct tbl *vp;
    258 	char UNINITIALIZED(*xp);
    259 	static char REPLY[] = "REPLY";
    260 
    261 	while ((optc = ksh_getopt(wp, &builtin_opt, "prsu,")) != EOF)
    262 		switch (optc) {
    263 #ifdef KSH
    264 		  case 'p':
    265 			if ((fd = coproc_getfd(R_OK, &emsg)) < 0) {
    266 				bi_errorf("-p: %s", emsg);
    267 				return 1;
    268 			}
    269 			break;
    270 #endif /* KSH */
    271 		  case 'r':
    272 			expandv = 0;
    273 			break;
    274 		  case 's':
    275 			history = 1;
    276 			break;
    277 		  case 'u':
    278 			if (!*(cp = builtin_opt.optarg))
    279 				fd = 0;
    280 			else if ((fd = check_fd(cp, R_OK, &emsg)) < 0) {
    281 				bi_errorf("-u: %s: %s", cp, emsg);
    282 				return 1;
    283 			}
    284 			break;
    285 		  case '?':
    286 			return 1;
    287 		}
    288 	wp += builtin_opt.optind;
    289 
    290 	if (*wp == NULL)
    291 		*--wp = REPLY;
    292 
    293 	/* Since we can't necessarily seek backwards on non-regular files,
    294 	 * don't buffer them so we can't read too much.
    295 	 */
    296 	shf = shf_reopen(fd, SHF_RD | SHF_INTERRUPT | can_seek(fd), shl_spare);
    297 
    298 	if ((cp = strchr(*wp, '?')) != NULL) {
    299 		*cp = 0;
    300 		if (isatty(fd)) {
    301 			/* at&t ksh says it prints prompt on fd if it's open
    302 			 * for writing and is a tty, but it doesn't do it
    303 			 * (it also doesn't check the interactive flag,
    304 			 * as is indicated in the Kornshell book).
    305 			 */
    306 			shellf("%s", cp+1);
    307 		}
    308 	}
    309 
    310 #ifdef KSH
    311 	/* If we are reading from the co-process for the first time,
    312 	 * make sure the other side of the pipe is closed first.  This allows
    313 	 * the detection of eof.
    314 	 *
    315 	 * This is not compatible with at&t ksh... the fd is kept so another
    316 	 * coproc can be started with same output, however, this means eof
    317 	 * can't be detected...  This is why it is closed here.
    318 	 * If this call is removed, remove the eof check below, too.
    319 	 * coproc_readw_close(fd);
    320 	 */
    321 #endif /* KSH */
    322 
    323 	if (history)
    324 		Xinit(xs, xp, 128, ATEMP);
    325 	expanding = 0;
    326 	Xinit(cs, cp, 128, ATEMP);
    327 	for (; *wp != NULL; wp++) {
    328 		for (cp = Xstring(cs, cp); ; ) {
    329 			if (c == '\n' || c == EOF)
    330 				break;
    331 			while (1) {
    332 				c = shf_getc(shf);
    333 				if (c == '\0'
    334 #ifdef OS2
    335 				    || c == '\r'
    336 #endif /* OS2 */
    337 				    )
    338 					continue;
    339 				if (c == EOF && shf_error(shf)
    340 				    && shf_errno(shf) == EINTR)
    341 				{
    342 					/* Was the offending signal one that
    343 					 * would normally kill a process?
    344 					 * If so, pretend the read was killed.
    345 					 */
    346 					ecode = fatal_trap_check();
    347 
    348 					/* non fatal (eg, CHLD), carry on */
    349 					if (!ecode) {
    350 						shf_clearerr(shf);
    351 						continue;
    352 					}
    353 				}
    354 				break;
    355 			}
    356 			if (history) {
    357 				Xcheck(xs, xp);
    358 				Xput(xs, xp, c);
    359 			}
    360 			Xcheck(cs, cp);
    361 			if (expanding) {
    362 				expanding = 0;
    363 				if (c == '\n') {
    364 					c = 0;
    365 					if (Flag(FTALKING_I) && isatty(fd)) {
    366 						/* set prompt in case this is
    367 						 * called from .profile or $ENV
    368 						 */
    369 						set_prompt(PS2, (Source *) 0);
    370 						pprompt(prompt, 0);
    371 					}
    372 				} else if (c != EOF)
    373 					Xput(cs, cp, c);
    374 				continue;
    375 			}
    376 			if (expandv && c == '\\') {
    377 				expanding = 1;
    378 				continue;
    379 			}
    380 			if (c == '\n' || c == EOF)
    381 				break;
    382 			if (ctype(c, C_IFS)) {
    383 				if (Xlength(cs, cp) == 0 && ctype(c, C_IFSWS))
    384 					continue;
    385 				if (wp[1])
    386 					break;
    387 			}
    388 			Xput(cs, cp, c);
    389 		}
    390 		/* strip trailing IFS white space from last variable */
    391 		if (!wp[1])
    392 			while (Xlength(cs, cp) && ctype(cp[-1], C_IFS)
    393 			       && ctype(cp[-1], C_IFSWS))
    394 				cp--;
    395 		Xput(cs, cp, '\0');
    396 		vp = global(*wp);
    397 		/* Must be done before setting export. */
    398 		if (vp->flag & RDONLY) {
    399 			shf_flush(shf);
    400 			bi_errorf("%s is read only", *wp);
    401 			return 1;
    402 		}
    403 		if (Flag(FEXPORT))
    404 			typeset(*wp, EXPORT, 0, 0, 0);
    405 		if (!setstr(vp, Xstring(cs, cp), KSH_RETURN_ERROR)) {
    406 		    shf_flush(shf);
    407 		    return 1;
    408 		}
    409 	}
    410 
    411 	shf_flush(shf);
    412 	if (history) {
    413 		Xput(xs, xp, '\0');
    414 		source->line++;
    415 		histsave(source->line, Xstring(xs, xp), 1);
    416 		Xfree(xs, xp);
    417 	}
    418 #ifdef KSH
    419 	/* if this is the co-process fd, close the file descriptor
    420 	 * (can get eof if and only if all processes are have died, ie,
    421 	 * coproc.njobs is 0 and the pipe is closed).
    422 	 */
    423 	if (c == EOF && !ecode)
    424 		coproc_read_close(fd);
    425 #endif /* KSH */
    426 
    427 	return ecode ? ecode : c == EOF;
    428 }
    429 
    430 int
    431 c_eval(wp)
    432 	char **wp;
    433 {
    434 	register struct source *s;
    435 	int rv;
    436 
    437 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
    438 		return 1;
    439 	s = pushs(SWORDS, ATEMP);
    440 	s->u.strv = wp + builtin_opt.optind;
    441 	if (!Flag(FPOSIX)) {
    442 		/*
    443 		 * Handle case where the command is empty due to failed
    444 		 * command substitution, eg, eval "$(false)".
    445 		 * In this case, shell() will not set/change exstat (because
    446 		 * compiled tree is empty), so will use this value.
    447 		 * subst_exstat is cleared in execute(), so should be 0 if
    448 		 * there were no substitutions.
    449 		 *
    450 		 * A strict reading of POSIX says we don't do this (though
    451 		 * it is traditionally done). [from 1003.2-1992]
    452 		 *    3.9.1: Simple Commands
    453 		 *	... If there is a command name, execution shall
    454 		 *	continue as described in 3.9.1.1.  If there
    455 		 *	is no command name, but the command contained a command
    456 		 *	substitution, the command shall complete with the exit
    457 		 *	status of the last command substitution
    458 		 *    3.9.1.1: Command Search and Execution
    459 		 *	...(1)...(a) If the command name matches the name of
    460 		 *	a special built-in utility, that special built-in
    461 		 *	utility shall be invoked.
    462 		 * 3.14.5: Eval
    463 		 *	... If there are no arguments, or only null arguments,
    464 		 *	eval shall return an exit status of zero.
    465 		 */
    466 		exstat = subst_exstat;
    467 	}
    468 
    469 	rv = shell(s, FALSE);
    470 	afree(s, ATEMP);
    471 	return rv;
    472 }
    473 
    474 int
    475 c_trap(wp)
    476 	char **wp;
    477 {
    478 	int i;
    479 	char *s;
    480 	register Trap *p;
    481 
    482 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
    483 		return 1;
    484 	wp += builtin_opt.optind;
    485 
    486 	if (*wp == NULL) {
    487 		int anydfl = 0;
    488 
    489 		for (p = sigtraps, i = SIGNALS+1; --i >= 0; p++) {
    490 			if (p->trap == NULL)
    491 				anydfl = 1;
    492 			else {
    493 				shprintf("trap -- ");
    494 				print_value_quoted(p->trap);
    495 				shprintf(" %s\n", p->name);
    496 			}
    497 		}
    498 #if 0 /* this is ugly and not clear POSIX needs it */
    499 		/* POSIX may need this so output of trap can be saved and
    500 		 * used to restore trap conditions
    501 		 */
    502 		if (anydfl) {
    503 			shprintf("trap -- -");
    504 			for (p = sigtraps, i = SIGNALS+1; --i >= 0; p++)
    505 				if (p->trap == NULL && p->name)
    506 					shprintf(" %s", p->name);
    507 			shprintf(newline);
    508 		}
    509 #else
    510 		__USE(anydfl);
    511 #endif
    512 		return 0;
    513 	}
    514 
    515 	/*
    516 	 * Use case sensitive lookup for first arg so the
    517 	 * command 'exit' isn't confused with the pseudo-signal
    518 	 * 'EXIT'.
    519 	 */
    520 	s = (gettrap(*wp, FALSE) == NULL) ? *wp++ : NULL; /* get command */
    521 	if (s != NULL && s[0] == '-' && s[1] == '\0')
    522 		s = NULL;
    523 
    524 	/* set/clear traps */
    525 	while (*wp != NULL) {
    526 		p = gettrap(*wp++, TRUE);
    527 		if (p == NULL) {
    528 			bi_errorf("bad signal %s", wp[-1]);
    529 			return 1;
    530 		}
    531 		settrap(p, s);
    532 	}
    533 	return 0;
    534 }
    535 
    536 int
    537 c_exitreturn(wp)
    538 	char **wp;
    539 {
    540 	int how = LEXIT;
    541 	int n;
    542 	char *arg;
    543 
    544 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
    545 		return 1;
    546 	arg = wp[builtin_opt.optind];
    547 
    548 	if (arg) {
    549 	    if (!getn(arg, &n)) {
    550 		    exstat = 1;
    551 		    warningf(TRUE, "%s: bad number", arg);
    552 	    } else
    553 		    exstat = n;
    554 	}
    555 	if (wp[0][0] == 'r') { /* return */
    556 		struct env *ep;
    557 
    558 		/* need to tell if this is exit or return so trap exit will
    559 		 * work right (POSIX)
    560 		 */
    561 		for (ep = e; ep; ep = ep->oenv)
    562 			if (STOP_RETURN(ep->type)) {
    563 				how = LRETURN;
    564 				break;
    565 			}
    566 	}
    567 
    568 	if (how == LEXIT && !really_exit && j_stopped_running()) {
    569 		really_exit = 1;
    570 		how = LSHELL;
    571 	}
    572 
    573 	quitenv();	/* get rid of any i/o redirections */
    574 	unwind(how);
    575 	/*NOTREACHED*/
    576 	return 0;
    577 }
    578 
    579 int
    580 c_brkcont(wp)
    581 	char **wp;
    582 {
    583 	int n, quit;
    584 	struct env *ep, *last_ep = (struct env *) 0;
    585 	char *arg;
    586 
    587 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
    588 		return 1;
    589 	arg = wp[builtin_opt.optind];
    590 
    591 	if (!arg)
    592 		n = 1;
    593 	else if (!bi_getn(arg, &n))
    594 		return 1;
    595 	quit = n;
    596 	if (quit <= 0) {
    597 		/* at&t ksh does this for non-interactive shells only - weird */
    598 		bi_errorf("%s: bad value", arg);
    599 		return 1;
    600 	}
    601 
    602 	/* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
    603 	for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
    604 		if (ep->type == E_LOOP) {
    605 			if (--quit == 0)
    606 				break;
    607 			ep->flags |= EF_BRKCONT_PASS;
    608 			last_ep = ep;
    609 		}
    610 
    611 	if (quit) {
    612 		/* at&t ksh doesn't print a message - just does what it
    613 		 * can.  We print a message 'cause it helps in debugging
    614 		 * scripts, but don't generate an error (ie, keep going).
    615 		 */
    616 		if (n == quit) {
    617 			warningf(TRUE, "%s: cannot %s", wp[0], wp[0]);
    618 			return 0;
    619 		}
    620 		/* POSIX says if n is too big, the last enclosing loop
    621 		 * shall be used.  Doesn't say to print an error but we
    622 		 * do anyway 'cause the user messed up.
    623 		 */
    624 		if (last_ep)
    625 			last_ep->flags &= ~EF_BRKCONT_PASS;
    626 		warningf(TRUE, "%s: can only %s %d level(s)",
    627 			wp[0], wp[0], n - quit);
    628 	}
    629 
    630 	unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
    631 	/*NOTREACHED*/
    632 }
    633 
    634 int
    635 c_set(wp)
    636 	char **wp;
    637 {
    638 	int argi, setargs;
    639 	struct block *l = e->loc;
    640 	register char **owp = wp;
    641 
    642 	if (wp[1] == NULL) {
    643 		static const char *const args [] = { "set", "-", NULL };
    644 		return c_typeset((char **)__UNCONST(args));
    645 	}
    646 
    647 	argi = parse_args(wp, OF_SET, &setargs);
    648 	if (argi < 0)
    649 		return 1;
    650 	/* set $# and $* */
    651 	if (setargs) {
    652 		owp = wp += argi - 1;
    653 		wp[0] = l->argv[0]; /* save $0 */
    654 		while (*++wp != NULL)
    655 			*wp = str_save(*wp, &l->area);
    656 		l->argc = wp - owp - 1;
    657 		l->argv = (char **) alloc(sizeofN(char *, l->argc+2), &l->area);
    658 		for (wp = l->argv; (*wp++ = *owp++) != NULL; )
    659 			;
    660 	}
    661 	/* POSIX says set exit status is 0, but old scripts that use
    662 	 * getopt(1), use the construct: set -- `getopt ab:c "$@"`
    663 	 * which assumes the exit value set will be that of the ``
    664 	 * (subst_exstat is cleared in execute() so that it will be 0
    665 	 * if there are no command substitutions).
    666 	 */
    667 	return Flag(FPOSIX) ? 0 : subst_exstat;
    668 }
    669 
    670 int
    671 c_unset(wp)
    672 	char **wp;
    673 {
    674 	register char *id;
    675 	int optc, unset_var = 1;
    676 	int ret = 0;
    677 
    678 	while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != EOF)
    679 		switch (optc) {
    680 		  case 'f':
    681 			unset_var = 0;
    682 			break;
    683 		  case 'v':
    684 			unset_var = 1;
    685 			break;
    686 		  case '?':
    687 			return 1;
    688 		}
    689 	wp += builtin_opt.optind;
    690 	for (; (id = *wp) != NULL; wp++)
    691 		if (unset_var) {	/* unset variable */
    692 			struct tbl *vp = global(id);
    693 
    694 			if (!(vp->flag & ISSET))
    695 			    ret = 1;
    696 			if ((vp->flag&RDONLY)) {
    697 				bi_errorf("%s is read only", vp->name);
    698 				return 1;
    699 			}
    700 			unset(vp, strchr(id, '[') ? 1 : 0);
    701 		} else {		/* unset function */
    702 			if (define(id, NULL))
    703 				ret = 1;
    704 		}
    705 	return ret;
    706 }
    707 
    708 int
    709 c_times(wp)
    710 	char **wp;
    711 {
    712 	struct tms all;
    713 
    714 	(void) ksh_times(&all);
    715 	shprintf("Shell: %8ss user ", clocktos(all.tms_utime));
    716 	shprintf("%8ss system\n", clocktos(all.tms_stime));
    717 	shprintf("Kids:  %8ss user ", clocktos(all.tms_cutime));
    718 	shprintf("%8ss system\n", clocktos(all.tms_cstime));
    719 
    720 	return 0;
    721 }
    722 
    723 /*
    724  * time pipeline (really a statement, not a built-in command)
    725  */
    726 int
    727 timex(t, f)
    728 	struct op *t;
    729 	int f;
    730 {
    731 #define TF_NOARGS	BIT(0)
    732 #define TF_NOREAL	BIT(1)		/* don't report real time */
    733 #define TF_POSIX	BIT(2)		/* report in posix format */
    734 	int rv = 0;
    735 	struct tms t0, t1, tms;
    736 	clock_t t0t, t1t = 0;
    737 	int tf = 0;
    738 	extern clock_t j_usrtime, j_systime; /* computed by j_wait */
    739 	char opts[1];
    740 
    741 	t0t = ksh_times(&t0);
    742 	if (t->left) {
    743 		/*
    744 		 * Two ways of getting cpu usage of a command: just use t0
    745 		 * and t1 (which will get cpu usage from other jobs that
    746 		 * finish while we are executing t->left), or get the
    747 		 * cpu usage of t->left. at&t ksh does the former, while
    748 		 * pdksh tries to do the later (the j_usrtime hack doesn't
    749 		 * really work as it only counts the last job).
    750 		 */
    751 		j_usrtime = j_systime = 0;
    752 		if (t->left->type == TCOM)
    753 			t->left->str = opts;
    754 		opts[0] = 0;
    755 		rv = execute(t->left, f | XTIME);
    756 		tf |= opts[0];
    757 		t1t = ksh_times(&t1);
    758 	} else
    759 		tf = TF_NOARGS;
    760 
    761 	if (tf & TF_NOARGS) { /* ksh93 - report shell times (shell+kids) */
    762 		tf |= TF_NOREAL;
    763 		tms.tms_utime = t0.tms_utime + t0.tms_cutime;
    764 		tms.tms_stime = t0.tms_stime + t0.tms_cstime;
    765 	} else {
    766 		tms.tms_utime = t1.tms_utime - t0.tms_utime + j_usrtime;
    767 		tms.tms_stime = t1.tms_stime - t0.tms_stime + j_systime;
    768 	}
    769 
    770 	if (!(tf & TF_NOREAL))
    771 		shf_fprintf(shl_out,
    772 			tf & TF_POSIX ? "real %8s\n" : "%8ss real ",
    773 			clocktos(t1t - t0t));
    774 	shf_fprintf(shl_out, tf & TF_POSIX ? "user %8s\n" : "%8ss user ",
    775 		clocktos(tms.tms_utime));
    776 	shf_fprintf(shl_out, tf & TF_POSIX ? "sys  %8s\n" : "%8ss system\n",
    777 		clocktos(tms.tms_stime));
    778 	shf_flush(shl_out);
    779 
    780 	return rv;
    781 }
    782 
    783 void
    784 timex_hook(t, app)
    785 	struct op *t;
    786 	char ** volatile *app;
    787 {
    788 	char **wp = *app;
    789 	int optc;
    790 	int i, j;
    791 	Getopt opt;
    792 
    793 	ksh_getopt_reset(&opt, 0);
    794 	opt.optind = 0;	/* start at the start */
    795 	while ((optc = ksh_getopt(wp, &opt, ":p")) != EOF)
    796 		switch (optc) {
    797 		  case 'p':
    798 			t->str[0] |= TF_POSIX;
    799 			break;
    800 		  case '?':
    801 			errorf("time: -%s unknown option", opt.optarg);
    802 		  case ':':
    803 			errorf("time: -%s requires an argument",
    804 				opt.optarg);
    805 		}
    806 	/* Copy command words down over options. */
    807 	if (opt.optind != 0) {
    808 		for (i = 0; i < opt.optind; i++)
    809 			afree(wp[i], ATEMP);
    810 		for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
    811 			;
    812 	}
    813 	if (!wp[0])
    814 		t->str[0] |= TF_NOARGS;
    815 	*app = wp;
    816 }
    817 
    818 static char *
    819 clocktos(t)
    820 	clock_t t;
    821 {
    822 	static char temp[22]; /* enough for 64 bit clock_t */
    823 	register int i;
    824 	register char *cp = temp + sizeof(temp);
    825 
    826 	/* note: posix says must use max precision, ie, if clk_tck is
    827 	 * 1000, must print 3 places after decimal (if non-zero, else 1).
    828 	 */
    829 	if (CLK_TCK != 100)	/* convert to 1/100'ths */
    830 	    t = (t < (clock_t)(1000000000/CLK_TCK)) ?
    831 		    (t * 100) / CLK_TCK : (t / CLK_TCK) * 100;
    832 
    833 	*--cp = '\0';
    834 	for (i = -2; i <= 0 || t > 0; i++) {
    835 		if (i == 0)
    836 			*--cp = '.';
    837 		*--cp = '0' + (char)(t%10);
    838 		t /= 10;
    839 	}
    840 	return cp;
    841 }
    842 
    843 /* exec with no args - args case is taken care of in comexec() */
    844 int
    845 c_exec(wp)
    846 	char ** wp;
    847 {
    848 	int i;
    849 
    850 	/* make sure redirects stay in place */
    851 	if (e->savefd != NULL) {
    852 		for (i = 0; i < NUFILE; i++) {
    853 			if (e->savefd[i] > 0)
    854 				close(e->savefd[i]);
    855 			/*
    856 			 * For ksh keep anything > 2 private,
    857 			 * for sh, let them be (POSIX says what
    858 			 * happens is unspecified and the bourne shell
    859 			 * keeps them open).
    860 			 */
    861 #ifdef KSH
    862 			if (i > 2 && e->savefd[i])
    863 				fd_clexec(i);
    864 #endif /* KSH */
    865 		}
    866 		e->savefd = NULL;
    867 	}
    868 	return 0;
    869 }
    870 
    871 /* dummy function, special case in comexec() */
    872 int
    873 c_builtin(wp)
    874 	char ** wp;
    875 {
    876 	return 0;
    877 }
    878 
    879 extern	int c_test ARGS((char **wp));		/* in c_test.c */
    880 extern	int c_ulimit ARGS((char **wp));		/* in c_ulimit.c */
    881 
    882 /* A leading = means assignments before command are kept;
    883  * a leading * means a POSIX special builtin;
    884  * a leading + means a POSIX regular builtin
    885  * (* and + should not be combined).
    886  */
    887 const struct builtin shbuiltins [] = {
    888 	{"*=.", c_dot},
    889 	{"*=:", c_label},
    890 	{"[", c_test},
    891 	{"*=break", c_brkcont},
    892 	{"=builtin", c_builtin},
    893 	{"*=continue", c_brkcont},
    894 	{"*=eval", c_eval},
    895 	{"*=exec", c_exec},
    896 	{"*=exit", c_exitreturn},
    897 	{"+false", c_label},
    898 	{"*=return", c_exitreturn},
    899 	{"*=set", c_set},
    900 	{"*=shift", c_shift},
    901 	{"=times", c_times},
    902 	{"*=trap", c_trap},
    903 	{"+=wait", c_wait},
    904 	{"+read", c_read},
    905 	{"test", c_test},
    906 	{"+true", c_label},
    907 	{"ulimit", c_ulimit},
    908 	{"+umask", c_umask},
    909 	{"*=unset", c_unset},
    910 #ifdef OS2
    911 	/* In OS2, the first line of a file can be "extproc name", which
    912 	 * tells the command interpreter (cmd.exe) to use name to execute
    913 	 * the file.  For this to be useful, ksh must ignore commands
    914 	 * starting with extproc and this does the trick...
    915 	 */
    916 	{"extproc", c_label},
    917 #endif /* OS2 */
    918 	{NULL, NULL}
    919 };
    920