1 /* $OpenBSD: c_sh.c,v 1.63 2018/04/09 17:53:36 tobias Exp $ */
4 * built-in Bourne commands
7 #include <sys/resource.h>
21 static void p_tv(struct shf
*, int, struct timeval
*, int, char *, char *);
22 static void p_ts(struct shf
*, int, struct timespec
*, int, char *, char *);
24 /* :, false and true */
28 return wp
[0][0] == 'f' ? 1 : 0;
34 struct block
*l
= genv
->loc
;
39 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
41 arg
= wp
[builtin_opt
.optind
];
44 evaluate(arg
, &val
, KSH_UNWIND_ERROR
, false);
49 bi_errorf("%s: bad number", arg
);
53 bi_errorf("nothing to shift");
56 l
->argv
[n
] = l
->argv
[0];
71 while ((optc
= ksh_getopt(wp
, &builtin_opt
, "S")) != -1)
79 cp
= wp
[builtin_opt
.optind
];
87 old_umask
= ~old_umask
;
89 for (i
= 0; i
< 3; i
++) {
92 for (j
= 0; j
< 3; j
++)
93 if (old_umask
& (1 << (8 - (3*i
+ j
))))
98 shprintf("%s\n", buf
);
100 shprintf("%#3.3o\n", old_umask
);
105 for (new_umask
= 0; *cp
>= '0' && *cp
<= '7'; cp
++)
106 new_umask
= new_umask
* 8 + (*cp
- '0');
108 bi_errorf("bad number");
112 /* symbolic format */
113 int positions
, new_val
;
116 old_umask
= umask(0);
117 umask(old_umask
); /* in case of error */
118 old_umask
= ~old_umask
;
119 new_umask
= old_umask
;
122 while (*cp
&& strchr("augo", *cp
))
138 positions
= 0111; /* default is a */
139 if (!strchr("=+-", op
= *cp
))
143 while (*cp
&& strchr("rwxugoXs", *cp
))
145 case 'r': new_val
|= 04; break;
146 case 'w': new_val
|= 02; break;
147 case 'x': new_val
|= 01; break;
148 case 'u': new_val
|= old_umask
>> 6;
150 case 'g': new_val
|= old_umask
>> 3;
152 case 'o': new_val
|= old_umask
>> 0;
154 case 'X': if (old_umask
& 0111)
157 case 's': /* ignored */
160 new_val
= (new_val
& 07) * positions
;
163 new_umask
&= ~new_val
;
166 new_umask
= new_val
|
167 (new_umask
& ~(positions
* 07));
170 new_umask
|= new_val
;
175 } else if (!strchr("=+-", *cp
))
179 bi_errorf("bad mask");
182 new_umask
= ~new_umask
;
198 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
201 if ((cp
= wp
[builtin_opt
.optind
]) == NULL
)
203 file
= search(cp
, search_path
, R_OK
, &err
);
205 bi_errorf("%s: %s", cp
, err
? strerror(err
) : "not found");
209 /* Set positional parameters? */
210 if (wp
[builtin_opt
.optind
+ 1]) {
211 argv
= wp
+ builtin_opt
.optind
;
212 argv
[0] = genv
->loc
->argv
[0]; /* preserve $0 */
213 for (argc
= 0; argv
[argc
+ 1]; argc
++)
219 i
= include(file
, argc
, argv
, 0);
220 if (i
< 0) { /* should not happen */
221 bi_errorf("%s: %s", cp
, strerror(errno
));
233 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
235 wp
+= builtin_opt
.optind
;
237 while (waitfor(NULL
, &sig
) >= 0)
242 rv
= waitfor(*wp
, &sig
);
244 rv
= sig
? sig
: 127; /* magic exit code: bad job-id */
253 int expand
= 1, savehist
= 0;
265 while ((optc
= ksh_getopt(wp
, &builtin_opt
, "prsu,")) != -1)
268 if ((fd
= coproc_getfd(R_OK
, &emsg
)) < 0) {
269 bi_errorf("-p: %s", emsg
);
280 if (!*(cp
= builtin_opt
.optarg
))
282 else if ((fd
= check_fd(cp
, R_OK
, &emsg
)) < 0) {
283 bi_errorf("-u: %s: %s", cp
, emsg
);
290 wp
+= builtin_opt
.optind
;
295 /* Since we can't necessarily seek backwards on non-regular files,
296 * don't buffer them so we can't read too much.
298 shf
= shf_reopen(fd
, SHF_RD
| SHF_INTERRUPT
| can_seek(fd
), shl_spare
);
300 if ((cp
= strchr(*wp
, '?')) != NULL
) {
303 /* at&t ksh says it prints prompt on fd if it's open
304 * for writing and is a tty, but it doesn't do it
305 * (it also doesn't check the interactive flag,
306 * as is indicated in the Kornshell book).
312 /* If we are reading from the co-process for the first time,
313 * make sure the other side of the pipe is closed first. This allows
314 * the detection of eof.
316 * This is not compatible with at&t ksh... the fd is kept so another
317 * coproc can be started with same output, however, this means eof
318 * can't be detected... This is why it is closed here.
319 * If this call is removed, remove the eof check below, too.
320 * coproc_readw_close(fd);
324 Xinit(xs
, xp
, 128, ATEMP
);
326 Xinit(cs
, cp
, 128, ATEMP
);
327 for (; *wp
!= NULL
; wp
++) {
328 for (cp
= Xstring(cs
, cp
); ; ) {
329 if (c
== '\n' || c
== EOF
)
335 if (c
== EOF
&& shf_error(shf
) &&
336 shf
->errno_
== EINTR
) {
337 /* Was the offending signal one that
338 * would normally kill a process?
339 * If so, pretend the read was killed.
341 ecode
= fatal_trap_check();
343 /* non fatal (eg, CHLD), carry on */
360 if (Flag(FTALKING_I
) && isatty(fd
)) {
361 /* set prompt in case this is
362 * called from .profile or $ENV
371 if (expand
&& c
== '\\') {
375 if (c
== '\n' || c
== EOF
)
377 if (ctype(c
, C_IFS
)) {
378 if (Xlength(cs
, cp
) == 0 && ctype(c
, C_IFSWS
))
385 /* strip trailing IFS white space from last variable */
387 while (Xlength(cs
, cp
) && ctype(cp
[-1], C_IFS
) &&
388 ctype(cp
[-1], C_IFSWS
))
392 /* Must be done before setting export. */
393 if (vp
->flag
& RDONLY
) {
395 bi_errorf("%s is read only", *wp
);
399 typeset(*wp
, EXPORT
, 0, 0, 0);
400 if (!setstr(vp
, Xstring(cs
, cp
), KSH_RETURN_ERROR
)) {
410 histsave(source
->line
, Xstring(xs
, xp
), 1);
413 /* if this is the co-process fd, close the file descriptor
414 * (can get eof if and only if all processes are have died, ie,
415 * coproc.njobs is 0 and the pipe is closed).
417 if (c
== EOF
&& !ecode
)
418 coproc_read_close(fd
);
420 return ecode
? ecode
: c
== EOF
;
429 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
431 s
= pushs(SWORDS
, ATEMP
);
432 s
->u
.strv
= wp
+ builtin_opt
.optind
;
435 * Handle case where the command is empty due to failed
436 * command substitution, eg, eval "$(false)".
437 * In this case, shell() will not set/change exstat (because
438 * compiled tree is empty), so will use this value.
439 * subst_exstat is cleared in execute(), so should be 0 if
440 * there were no substitutions.
442 * A strict reading of POSIX says we don't do this (though
443 * it is traditionally done). [from 1003.2-1992]
444 * 3.9.1: Simple Commands
445 * ... If there is a command name, execution shall
446 * continue as described in 3.9.1.1. If there
447 * is no command name, but the command contained a command
448 * substitution, the command shall complete with the exit
449 * status of the last command substitution
450 * 3.9.1.1: Command Search and Execution
451 * ...(1)...(a) If the command name matches the name of
452 * a special built-in utility, that special built-in
453 * utility shall be invoked.
455 * ... If there are no arguments, or only null arguments,
456 * eval shall return an exit status of zero.
458 exstat
= subst_exstat
;
461 rv
= shell(s
, false);
473 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
475 wp
+= builtin_opt
.optind
;
478 for (p
= sigtraps
, i
= NSIG
+1; --i
>= 0; p
++) {
479 if (p
->trap
!= NULL
) {
480 shprintf("trap -- ");
481 print_value_quoted(p
->trap
);
482 shprintf(" %s\n", p
->name
);
489 * Use case sensitive lookup for first arg so the
490 * command 'exit' isn't confused with the pseudo-signal
493 s
= (gettrap(*wp
, false) == NULL
) ? *wp
++ : NULL
; /* get command */
494 if (s
!= NULL
&& s
[0] == '-' && s
[1] == '\0')
497 /* set/clear traps */
498 while (*wp
!= NULL
) {
499 p
= gettrap(*wp
++, true);
501 bi_errorf("bad signal %s", wp
[-1]);
510 c_exitreturn(char **wp
)
516 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
518 arg
= wp
[builtin_opt
.optind
];
521 if (!getn(arg
, &n
)) {
523 warningf(true, "%s: bad number", arg
);
527 if (wp
[0][0] == 'r') { /* return */
530 /* need to tell if this is exit or return so trap exit will
533 for (ep
= genv
; ep
; ep
= ep
->oenv
)
534 if (STOP_RETURN(ep
->type
)) {
540 if (how
== LEXIT
&& !really_exit
&& j_stopped_running()) {
545 quitenv(NULL
); /* get rid of any i/o redirections */
555 struct env
*ep
, *last_ep
= NULL
;
558 if (ksh_getopt(wp
, &builtin_opt
, null
) == '?')
560 arg
= wp
[builtin_opt
.optind
];
564 else if (!bi_getn(arg
, &n
))
568 /* at&t ksh does this for non-interactive shells only - weird */
569 bi_errorf("%s: bad value", arg
);
573 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
574 for (ep
= genv
; ep
&& !STOP_BRKCONT(ep
->type
); ep
= ep
->oenv
)
575 if (ep
->type
== E_LOOP
) {
578 ep
->flags
|= EF_BRKCONT_PASS
;
583 /* at&t ksh doesn't print a message - just does what it
584 * can. We print a message 'cause it helps in debugging
585 * scripts, but don't generate an error (ie, keep going).
588 warningf(true, "%s: cannot %s", wp
[0], wp
[0]);
591 /* POSIX says if n is too big, the last enclosing loop
592 * shall be used. Doesn't say to print an error but we
593 * do anyway 'cause the user messed up.
596 last_ep
->flags
&= ~EF_BRKCONT_PASS
;
597 warningf(true, "%s: can only %s %d level(s)",
598 wp
[0], wp
[0], n
- quit
);
601 unwind(*wp
[0] == 'b' ? LBREAK
: LCONTIN
);
609 struct block
*l
= genv
->loc
;
613 static const char *const args
[] = { "set", "-", NULL
};
614 return c_typeset((char **) args
);
617 argi
= parse_args(wp
, OF_SET
, &setargs
);
622 owp
= wp
+= argi
- 1;
623 wp
[0] = l
->argv
[0]; /* save $0 */
624 while (*++wp
!= NULL
)
625 *wp
= str_save(*wp
, &l
->area
);
626 l
->argc
= wp
- owp
- 1;
627 l
->argv
= areallocarray(NULL
, l
->argc
+2, sizeof(char *), &l
->area
);
628 for (wp
= l
->argv
; (*wp
++ = *owp
++) != NULL
; )
631 /* POSIX says set exit status is 0, but old scripts that use
632 * getopt(1), use the construct: set -- `getopt ab:c "$@"`
633 * which assumes the exit value set will be that of the ``
634 * (subst_exstat is cleared in execute() so that it will be 0
635 * if there are no command substitutions).
637 return Flag(FPOSIX
) ? 0 : subst_exstat
;
644 int optc
, unset_var
= 1;
646 while ((optc
= ksh_getopt(wp
, &builtin_opt
, "fv")) != -1)
657 wp
+= builtin_opt
.optind
;
658 for (; (id
= *wp
) != NULL
; wp
++)
659 if (unset_var
) { /* unset variable */
660 struct tbl
*vp
= global(id
);
662 if ((vp
->flag
&RDONLY
)) {
663 bi_errorf("%s is read only", vp
->name
);
666 unset(vp
, strchr(id
, '[') ? 1 : 0);
667 } else { /* unset function */
674 p_tv(struct shf
*shf
, int posix
, struct timeval
*tv
, int width
, char *prefix
,
678 shf_fprintf(shf
, "%s%*lld.%02ld%s", prefix
? prefix
: "",
679 width
, (long long)tv
->tv_sec
, tv
->tv_usec
/ 10000, suffix
);
681 shf_fprintf(shf
, "%s%*lldm%02lld.%02lds%s", prefix
? prefix
: "",
682 width
, (long long)tv
->tv_sec
/ 60,
683 (long long)tv
->tv_sec
% 60,
684 tv
->tv_usec
/ 10000, suffix
);
688 p_ts(struct shf
*shf
, int posix
, struct timespec
*ts
, int width
, char *prefix
,
692 shf_fprintf(shf
, "%s%*lld.%02ld%s", prefix
? prefix
: "",
693 width
, (long long)ts
->tv_sec
, ts
->tv_nsec
/ 10000000,
696 shf_fprintf(shf
, "%s%*lldm%02lld.%02lds%s", prefix
? prefix
: "",
697 width
, (long long)ts
->tv_sec
/ 60,
698 (long long)ts
->tv_sec
% 60,
699 ts
->tv_nsec
/ 10000000, suffix
);
708 (void) getrusage(RUSAGE_SELF
, &usage
);
709 p_tv(shl_stdout
, 0, &usage
.ru_utime
, 0, NULL
, " ");
710 p_tv(shl_stdout
, 0, &usage
.ru_stime
, 0, NULL
, "\n");
712 (void) getrusage(RUSAGE_CHILDREN
, &usage
);
713 p_tv(shl_stdout
, 0, &usage
.ru_utime
, 0, NULL
, " ");
714 p_tv(shl_stdout
, 0, &usage
.ru_stime
, 0, NULL
, "\n");
720 * time pipeline (really a statement, not a built-in command)
723 timex(struct op
*t
, int f
, volatile int *xerrok
)
725 #define TF_NOARGS BIT(0)
726 #define TF_NOREAL BIT(1) /* don't report real time */
727 #define TF_POSIX BIT(2) /* report in posix format */
729 struct rusage ru0
, ru1
, cru0
, cru1
;
730 struct timeval usrtime
, systime
;
731 struct timespec ts0
, ts1
, ts2
;
733 extern struct timeval j_usrtime
, j_systime
; /* computed by j_wait */
735 clock_gettime(CLOCK_MONOTONIC
, &ts0
);
736 getrusage(RUSAGE_SELF
, &ru0
);
737 getrusage(RUSAGE_CHILDREN
, &cru0
);
740 * Two ways of getting cpu usage of a command: just use t0
741 * and t1 (which will get cpu usage from other jobs that
742 * finish while we are executing t->left), or get the
743 * cpu usage of t->left. at&t ksh does the former, while
744 * pdksh tries to do the later (the j_usrtime hack doesn't
745 * really work as it only counts the last job).
747 timerclear(&j_usrtime
);
748 timerclear(&j_systime
);
749 rv
= execute(t
->left
, f
| XTIME
, xerrok
);
750 if (t
->left
->type
== TCOM
)
751 tf
|= t
->left
->str
[0];
752 clock_gettime(CLOCK_MONOTONIC
, &ts1
);
753 getrusage(RUSAGE_SELF
, &ru1
);
754 getrusage(RUSAGE_CHILDREN
, &cru1
);
758 if (tf
& TF_NOARGS
) { /* ksh93 - report shell times (shell+kids) */
760 timeradd(&ru0
.ru_utime
, &cru0
.ru_utime
, &usrtime
);
761 timeradd(&ru0
.ru_stime
, &cru0
.ru_stime
, &systime
);
763 timersub(&ru1
.ru_utime
, &ru0
.ru_utime
, &usrtime
);
764 timeradd(&usrtime
, &j_usrtime
, &usrtime
);
765 timersub(&ru1
.ru_stime
, &ru0
.ru_stime
, &systime
);
766 timeradd(&systime
, &j_systime
, &systime
);
769 if (!(tf
& TF_NOREAL
)) {
770 timespecsub(&ts1
, &ts0
, &ts2
);
772 p_ts(shl_out
, 1, &ts2
, 5, "real ", "\n");
774 p_ts(shl_out
, 0, &ts2
, 5, NULL
, " real ");
777 p_tv(shl_out
, 1, &usrtime
, 5, "user ", "\n");
779 p_tv(shl_out
, 0, &usrtime
, 5, NULL
, " user ");
781 p_tv(shl_out
, 1, &systime
, 5, "sys ", "\n");
783 p_tv(shl_out
, 0, &systime
, 5, NULL
, " system\n");
790 timex_hook(struct op
*t
, char **volatile *app
)
797 ksh_getopt_reset(&opt
, 0);
798 opt
.optind
= 0; /* start at the start */
799 while ((optc
= ksh_getopt(wp
, &opt
, ":p")) != -1)
802 t
->str
[0] |= TF_POSIX
;
805 errorf("time: -%s unknown option", opt
.optarg
);
807 errorf("time: -%s requires an argument",
810 /* Copy command words down over options. */
811 if (opt
.optind
!= 0) {
812 for (i
= 0; i
< opt
.optind
; i
++)
814 for (i
= 0, j
= opt
.optind
; (wp
[i
] = wp
[j
]); i
++, j
++)
818 t
->str
[0] |= TF_NOARGS
;
822 /* exec with no args - args case is taken care of in comexec() */
828 /* make sure redirects stay in place */
829 if (genv
->savefd
!= NULL
) {
830 for (i
= 0; i
< NUFILE
; i
++) {
831 if (genv
->savefd
[i
] > 0)
832 close(genv
->savefd
[i
]);
834 * For ksh keep anything > 2 private,
835 * for sh, let them be (POSIX says what
836 * happens is unspecified and the bourne shell
839 if (!Flag(FSH
) && i
> 2 && genv
->savefd
[i
])
840 fcntl(i
, F_SETFD
, FD_CLOEXEC
);
851 bi_errorf("too many arguments");
855 /* Can't suspend an orphaned process group. */
856 pid_t parent
= getppid();
857 if (getpgid(parent
) == getpgid(0) ||
858 getsid(parent
) != getsid(0)) {
859 bi_errorf("can't suspend a login shell");
867 /* dummy function, special case in comexec() */
874 extern int c_test(char **wp
); /* in c_test.c */
875 extern int c_ulimit(char **wp
); /* in c_ulimit.c */
877 /* A leading = means assignments before command are kept;
878 * a leading * means a POSIX special builtin;
879 * a leading + means a POSIX regular builtin
880 * (* and + should not be combined).
882 const struct builtin shbuiltins
[] = {
886 {"*=break", c_brkcont
},
887 {"=builtin", c_builtin
},
888 {"*=continue", c_brkcont
},
891 {"*=exit", c_exitreturn
},
893 {"*=return", c_exitreturn
},
895 {"*=shift", c_shift
},
896 {"*=times", c_times
},
902 {"ulimit", c_ulimit
},
904 {"*=unset", c_unset
},
905 {"suspend", c_suspend
},