1 /* $OpenBSD: c_ksh.c,v 1.37 2015/09/10 22:48:58 nicm Exp $ */
2 /* $OpenBSD: c_sh.c,v 1.46 2015/07/20 20:46:24 guenther Exp $ */
3 /* $OpenBSD: c_test.c,v 1.18 2009/03/01 20:11:06 otto Exp $ */
4 /* $OpenBSD: c_ulimit.c,v 1.19 2013/11/28 10:33:37 sobrado Exp $ */
7 * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
8 * 2010, 2011, 2012, 2013, 2014, 2015, 2016
9 * mirabilos <m@mirbsd.org>
11 * Provided that these terms and disclaimer and all copyright notices
12 * are retained or reproduced in an accompanying document, permission
13 * is granted to deal in this work without restriction, including un-
14 * limited rights to use, publicly perform, distribute, sell, modify,
15 * merge, give away, or sublicence.
17 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
18 * the utmost extent permitted by applicable law, neither express nor
19 * implied; without malicious intent or gross negligence. In no event
20 * may a licensor, author or contributor be held liable for indirect,
21 * direct, other damage, loss, or other issues arising in any way out
22 * of dealing in the work, even if advised of the possibility of such
23 * damage or existence of a defect, except proven that it results out
24 * of said person's immediate fault when using the work as intended.
30 #if HAVE_SYS_BSDTYPES_H
31 #include <sys/bsdtypes.h>
34 #include <sys/select.h>
41 __RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.293 2016/01/20 21:34:11 tg Exp $");
45 * use killpg if < -1 since -1 does special things
46 * for some non-killpg-endowed kills
48 #define mksh_kill(p,s) ((p) < -1 ? killpg(-(p), (s)) : kill((p), (s)))
50 /* cross fingers and hope kill is killpg-endowed */
51 #define mksh_kill kill
54 /* XXX conditions correct? */
55 #if !defined(RLIM_INFINITY) && !defined(MKSH_NO_LIMITS)
56 #define MKSH_NO_LIMITS 1
60 #define c_ulimit c_true
63 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
64 static int c_suspend(const char **);
67 /* getn() that prints error */
69 bi_getn(const char *as, int *ai)
73 if (!(rv = getn(as, ai)))
74 bi_errorf("%s: %s", as, "bad number");
79 c_true(const char **wp MKSH_A_UNUSED)
85 c_false(const char **wp MKSH_A_UNUSED)
91 * A leading = means assignments before command are kept.
92 * A leading * means a POSIX special builtin.
94 const struct builtin mkshbuiltins[] = {
98 /* no =: AT&T manual wrong */
100 {"*=break", c_brkcont},
101 {Tgbuiltin, c_builtin},
104 /* dash compatibility hack */
106 {Tcommand, c_command},
107 {"*=continue", c_brkcont},
111 {"*=exit", c_exitreturn},
112 {Tsgexport, c_typeset},
115 {"getopts", c_getopts},
116 {"=global", c_typeset},
124 {Tsgreadonly, c_typeset},
125 {"realpath", c_realpath},
126 {"rename", c_rename},
127 {"*=return", c_exitreturn},
129 {"*=shift", c_shift},
131 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
132 {"suspend", c_suspend},
135 {"*=times", c_times},
138 {T_typeset, c_typeset},
139 {"ulimit", c_ulimit},
141 {Tunalias, c_unalias},
142 {"*=unset", c_unset},
144 {"whence", c_whence},
145 #ifndef MKSH_UNEMPLOYED
149 #ifndef MKSH_NO_CMDLINE_EDITING
155 #ifdef MKSH_PRINTF_BUILTIN
162 /* alias to "true" for historical reasons */
163 {"domainname", c_true},
168 {NULL, (int (*)(const char **))NULL}
176 static const struct t_op {
206 static const struct t_op b_ops[] = {
224 static int test_oexpr(Test_env *, bool);
225 static int test_aexpr(Test_env *, bool);
226 static int test_nexpr(Test_env *, bool);
227 static int test_primary(Test_env *, bool);
228 static Test_op ptest_isa(Test_env *, Test_meta);
229 static const char *ptest_getopnd(Test_env *, Test_op, bool);
230 static void ptest_error(Test_env *, int, const char *);
231 static void kill_fmt_entry(char *, size_t, unsigned int, const void *);
232 static void p_time(struct shf *, bool, long, int, int,
233 const char *, const char *);
236 c_pwd(const char **wp)
239 bool physical = tobool(Flag(FPHYSICAL));
240 char *p, *allocd = NULL;
242 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
253 wp += builtin_opt.optind;
256 bi_errorf("too many arguments");
259 p = current_wd[0] ? (physical ? allocd = do_realpath(current_wd) :
261 /* LINTED use of access */
262 if (p && access(p, R_OK) < 0)
264 if (!p && !(p = allocd = ksh_get_wd())) {
265 bi_errorf("%s: %s", "can't determine current directory",
270 afree(allocd, ATEMP);
274 static const char *s_ptr;
275 static int s_get(void);
276 static void s_put(int);
279 c_print(const char **wp)
285 /* print newline; expand backslash sequences */
286 bool po_nl = true, po_exp = true;
287 /* print to history instead of file descriptor / stdout */
288 bool po_hist = false;
290 if (wp[0][0] == 'e') {
293 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
296 * MidnightBSD /bin/sh needs a BSD echo, that is,
297 * one that supports -e but does not enable it by
304 #ifndef MKSH_MIDNIGHTBSD01ASH_COMPAT
308 /* Debian Policy 10.4 compliant "echo" builtin */
309 if (*wp && !strcmp(*wp, "-n")) {
310 /* recognise "-n" only as the first arg */
314 /* print everything as-is */
317 bool new_exp = po_exp, new_nl = po_nl;
320 * a compromise between sysV and BSD echo commands:
321 * escape sequences are enabled by default, and -n,
322 * -e and -E are recognised if they appear in argu-
323 * ments with no illegal options (ie, echo -nq will
325 * Different from sysV echo since options are reco-
326 * gnised, different from BSD echo since escape se-
327 * quences are enabled by default.
331 if ((s = *wp) && *s++ == '-' && *s) {
333 switch ((c = *s++)) {
336 goto print_tradparse_ch;
339 goto print_tradparse_ch;
342 goto print_tradparse_ch;
347 goto print_tradparse_arg;
352 /* "print" builtin */
353 const char *opts = "npRrsu,";
355 /* print a "--" argument */
356 bool po_pminusminus = false;
358 while ((c = ksh_getopt(wp, &builtin_opt, opts)) != -1)
367 if ((fd = coproc_getfd(W_OK, &emsg)) < 0) {
368 bi_errorf("-p: %s", emsg);
373 /* fake BSD echo command */
374 po_pminusminus = true;
385 if (!*(s = builtin_opt.optarg))
387 else if ((fd = check_fd(s, W_OK, &emsg)) < 0) {
388 bi_errorf("-u%s: %s", s, emsg);
396 if (!(builtin_opt.info & GI_MINUSMINUS)) {
397 /* treat a lone "-" like "--" */
398 if (wp[builtin_opt.optind] &&
399 ksh_isdash(wp[builtin_opt.optind]))
400 builtin_opt.optind++;
401 } else if (po_pminusminus)
402 builtin_opt.optind--;
403 wp += builtin_opt.optind;
406 Xinit(xs, xp, 128, ATEMP);
411 while ((c = *s++) != '\0') {
413 if (po_exp && c == '\\') {
415 c = unbksl(false, s_get, s_put);
418 /* rejected by generic function */
419 switch ((c = *s++)) {
422 /* AT&T brain damage */
431 } else if ((unsigned int)c > 0xFF) {
432 /* generic function returned Unicode */
435 ts[utf_wctomb(ts, c - 0x100)] = 0;
456 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
459 size_t len = Xlength(xs, xp);
460 bool po_coproc = false;
464 * Ensure we aren't killed by a SIGPIPE while writing to
465 * a coprocess. AT&T ksh doesn't seem to do this (seems
466 * to just check that the co-process is alive which is
469 if (coproc.write >= 0 && coproc.write == fd) {
471 opipe = block_pipe();
478 if ((nwritten = write(fd, s, len)) < 0) {
479 if (errno == EINTR) {
482 /* give the user a chance to ^C out */
484 /* interrupted, try again */
486 opipe = block_pipe();
509 s_put(int c MKSH_A_UNUSED)
515 c_whence(const char **wp)
519 bool pflag = false, vflag = false, Vflag = false;
520 int rv = 0, optc, fcflags;
521 bool iam_whence = wp[0][0] == 'w';
522 const char *opts = iam_whence ? "pv" : "pvV";
524 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1)
538 wp += builtin_opt.optind;
540 fcflags = FC_BI | FC_PATH | FC_FUNC;
542 /* Note that -p on its own is deal with in comexec() */
544 fcflags |= FC_DEFPATH;
546 * Convert command options to whence options - note that
547 * command -pV uses a different path search than whence -v
548 * or whence -pv. This should be considered a feature.
553 fcflags &= ~(FC_BI | FC_FUNC);
555 while ((vflag || rv == 0) && (id = *wp++) != NULL) {
560 tp = ktsearch(&keywords, id, h = hash(id));
562 tp = ktsearch(&aliases, id, h ? h : hash(id));
563 if (tp && !(tp->flag & ISSET))
567 tp = findcom(id, fcflags);
568 if (vflag || (tp->type != CALIAS && tp->type != CEXEC &&
569 tp->type != CTALIAS))
570 shf_puts(id, shl_stdout);
577 shf_puts(" is a", shl_stdout);
585 shf_putc(' ', shl_stdout);
593 shf_puts("reserved word", shl_stdout);
597 shprintf("n %s%s for ",
598 (tp->flag & EXPORT) ? "exported " : null,
600 if (!iam_whence && !vflag)
601 shprintf("%s %s=", Talias, id);
602 print_value_quoted(shl_stdout, tp->val.s);
606 if (tp->flag & EXPORT)
607 shf_puts("n exported", shl_stdout);
608 if (tp->flag & TRACE)
609 shf_puts(" traced", shl_stdout);
610 if (!(tp->flag & ISSET)) {
611 shf_puts(" undefined", shl_stdout);
613 shprintf(" (autoload from %s)",
616 shf_puts(T_function, shl_stdout);
621 if (tp->flag & SPEC_BI)
622 shf_puts("special ", shl_stdout);
623 shprintf("%s %s", "shell", Tbuiltin);
628 if (tp->flag & ISSET) {
630 shf_puts("is ", shl_stdout);
631 if (tp->type == CTALIAS)
632 shprintf("a tracked %s%s for ",
633 (tp->flag & EXPORT) ?
637 shf_puts(tp->val.s, shl_stdout);
640 shf_puts("not found", shl_stdout);
645 shf_puts(" is *GOK*", shl_stdout);
649 shf_putc('\n', shl_stdout);
654 /* Deal with command -vV - command -p dealt with in comexec() */
656 c_command(const char **wp)
659 * Let c_whence do the work. Note that c_command() must be
660 * a distinct function from c_whence() (tested in comexec()).
662 return (c_whence(wp));
665 /* typeset, global, export, and readonly */
666 static void c_typeset_vardump(struct tbl *, uint32_t, int, bool, bool);
667 static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
670 c_typeset(const char **wp)
673 uint32_t fset = 0, fclr = 0, flag;
674 int thing = 0, field = 0, base = 0, i;
677 const char *fieldstr = NULL, *basestr = NULL;
678 bool localv = false, func = false, pflag = false, istset = true;
679 enum namerefflag new_refflag = SRF_NOP;
697 /* called with 'typeset -' */
706 /* see comment below regarding possible opions */
707 opts = istset ? "L#R#UZ#afi#lnprtux" : "p";
709 builtin_opt.flags |= GF_PLUSOPT;
711 * AT&T ksh seems to have 0-9 as options which are multiplied
712 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
713 * sets right justify in a field of 12). This allows options
714 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
715 * does not allow the number to be specified as a separate argument
716 * Here, the number must follow the RLZi option, but is optional
717 * (see the # kludge in ksh_getopt()).
719 while ((i = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
724 fieldstr = builtin_opt.optarg;
728 fieldstr = builtin_opt.optarg;
732 * AT&T ksh uses u, but this conflicts with
733 * upper/lower case. If this option is changed,
734 * need to change the -U below as well
740 fieldstr = builtin_opt.optarg;
744 * this is supposed to set (-a) or unset (+a) the
745 * indexed array attribute; it does nothing on an
746 * existing regular string or indexed array though
754 basestr = builtin_opt.optarg;
760 new_refflag = (builtin_opt.info & GI_PLUS) ?
761 SRF_DISABLE : SRF_ENABLE;
763 /* export, readonly: POSIX -p flag */
765 /* typeset: show values as well */
777 /* upper case / autoload */
786 if (builtin_opt.info & GI_PLUS) {
797 if (fieldstr && !bi_getn(fieldstr, &field))
800 if (!getn(basestr, &base)) {
801 bi_errorf("%s: %s", "bad integer base", basestr);
804 if (base < 1 || base > 36)
808 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
809 (wp[builtin_opt.optind][0] == '-' ||
810 wp[builtin_opt.optind][0] == '+') &&
811 wp[builtin_opt.optind][1] == '\0') {
812 thing = wp[builtin_opt.optind][0];
813 builtin_opt.optind++;
816 if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
817 new_refflag != SRF_NOP)) {
818 bi_errorf("only -t, -u and -x options may be used with -f");
821 if (wp[builtin_opt.optind]) {
823 * Take care of exclusions.
824 * At this point, flags in fset are cleared in fclr and vice
825 * versa. This property should be preserved.
828 /* LCASEV has priority over UCASEV_AL */
831 /* LJUST has priority over RJUST */
833 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
839 * Setting these attributes clears the others, unless they
840 * are also set in this command
842 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
843 INTEGER | INT_U | INT_L)) || new_refflag != SRF_NOP)
844 fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
845 LCASEV | INTEGER | INT_U | INT_L);
847 if (new_refflag != SRF_NOP) {
848 fclr &= ~(ARRAY | ASSOC);
849 fset &= ~(ARRAY | ASSOC);
852 if (new_refflag == SRF_DISABLE)
856 /* set variables and attributes */
857 if (wp[builtin_opt.optind] &&
858 /* not "typeset -p varname" */
859 !(!func && pflag && !(fset | fclr))) {
865 for (i = builtin_opt.optind; wp[i]; i++) {
867 f = findfunc(wp[i], hash(wp[i]),
868 tobool(fset & UCASEV_AL));
870 /* AT&T ksh does ++rv: bogus */
878 fpFUNCTf(shl_stdout, 0,
879 tobool(f->flag & FKSH),
881 shf_putc('\n', shl_stdout);
883 } else if (!typeset(wp[i], fset, fclr, field, base)) {
884 bi_errorf("%s: %s", wp[i], "is not an identifier");
891 /* list variables and attributes */
893 /* no difference at this point.. */
896 for (l = e->loc; l; l = l->next) {
897 for (p = ktsort(&l->funs); (vp = *p++); ) {
898 if (flag && (vp->flag & flag) == 0)
901 fpFUNCTf(shl_stdout, 0,
902 tobool(vp->flag & FKSH),
903 vp->name, vp->val.t);
905 shf_puts(vp->name, shl_stdout);
906 shf_putc('\n', shl_stdout);
909 } else if (wp[builtin_opt.optind]) {
910 for (i = builtin_opt.optind; wp[i]; i++) {
911 varsearch(e->loc, &vp, wp[i], hash(wp[i]));
912 c_typeset_vardump(vp, flag, thing, pflag, istset);
915 c_typeset_vardump_recursive(e->loc, flag, thing, pflag, istset);
920 c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
921 bool pflag, bool istset)
923 struct tbl **blockvars, *vp;
926 c_typeset_vardump_recursive(l->next, flag, thing, pflag, istset);
927 blockvars = ktsort(&l->vars);
928 while ((vp = *blockvars++))
929 c_typeset_vardump(vp, flag, thing, pflag, istset);
930 /*XXX doesn’t this leak? */
934 c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, bool pflag,
945 * See if the parameter is set (for arrays, if any
948 for (tvp = vp; tvp; tvp = tvp->u.array)
949 if (tvp->flag & ISSET) {
955 * Check attributes - note that all array elements
956 * have (should have?) the same attributes, so checking
957 * the first is sufficient.
959 * Report an unset param only if the user has
960 * explicitly given it some attribute (like export);
961 * otherwise, after "echo $FOO", we would report FOO...
963 if (!any_set && !(vp->flag & USERATTRIB))
965 if (flag && (vp->flag & flag) == 0)
967 if (!(vp->flag & ARRAY))
968 /* optimise later conditionals */
972 * Ignore array elements that aren't set unless there
973 * are no set elements, in which case the first is
976 if (any_set && !(vp->flag & ISSET))
979 if (!thing && !flag) {
981 shprintf("%s %s %s\n", Tset, "-A", vp->name);
985 * AT&T ksh prints things like export, integer,
986 * leftadj, zerofill, etc., but POSIX says must
987 * be suitable for re-entry...
989 shprintf("%s %s", Ttypeset, "");
990 if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
991 shprintf("%s ", "-n");
992 if ((vp->flag & INTEGER))
993 shprintf("%s ", "-i");
994 if ((vp->flag & EXPORT))
995 shprintf("%s ", "-x");
996 if ((vp->flag & RDONLY))
997 shprintf("%s ", "-r");
998 if ((vp->flag & TRACE))
999 shprintf("%s ", "-t");
1000 if ((vp->flag & LJUST))
1001 shprintf("-L%d ", vp->u2.field);
1002 if ((vp->flag & RJUST))
1003 shprintf("-R%d ", vp->u2.field);
1004 if ((vp->flag & ZEROFIL))
1005 shprintf("%s ", "-Z");
1006 if ((vp->flag & LCASEV))
1007 shprintf("%s ", "-l");
1008 if ((vp->flag & UCASEV_AL))
1009 shprintf("%s ", "-u");
1010 if ((vp->flag & INT_U))
1011 shprintf("%s ", "-U");
1013 shprintf("%s %s", istset ? Ttypeset :
1014 (flag & EXPORT) ? Texport : Treadonly, "");
1017 shprintf("%s[%lu]", vp->name, arrayindex(vp));
1019 shf_puts(vp->name, shl_stdout);
1020 if ((!thing && !flag && pflag) ||
1021 (thing == '-' && (vp->flag & ISSET))) {
1023 shf_putc('=', shl_stdout);
1024 /* AT&T ksh can't have justified integers... */
1025 if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
1026 shf_puts(s, shl_stdout);
1028 print_value_quoted(shl_stdout, s);
1030 shf_putc('\n', shl_stdout);
1033 * Only report first 'element' of an array with
1038 } while ((vp = vp->u.array));
1042 c_alias(const char **wp)
1044 struct table *t = &aliases;
1045 int rv = 0, prefix = 0;
1046 bool rflag = false, tflag, Uflag = false, pflag = false;
1050 builtin_opt.flags |= GF_PLUSOPT;
1051 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
1052 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
1056 t = NULL; /* fix "alias -dt" */
1072 * kludge for tracked alias initialization
1073 * (don't do a path search, just make an entry)
1088 wp += builtin_opt.optind;
1090 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
1091 (wp[0][0] == '-' || wp[0][0] == '+') && wp[0][1] == '\0') {
1096 tflag = t == &taliases;
1098 /* "hash -r" means reset all the tracked aliases.. */
1100 static const char *args[] = {
1101 Tunalias, "-ta", NULL
1104 if (!tflag || *wp) {
1105 shprintf("%s: -r flag can only be used with -t"
1106 " and without arguments\n", Talias);
1109 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1110 return (c_unalias(args));
1114 struct tbl *ap, **p;
1116 for (p = ktsort(t); (ap = *p++) != NULL; )
1117 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
1119 shprintf("%s ", Talias);
1120 shf_puts(ap->name, shl_stdout);
1121 if (prefix != '+') {
1122 shf_putc('=', shl_stdout);
1123 print_value_quoted(shl_stdout, ap->val.s);
1125 shf_putc('\n', shl_stdout);
1129 for (; *wp != NULL; wp++) {
1130 const char *alias = *wp, *val, *newval;
1131 char *xalias = NULL;
1135 if ((val = cstrchr(alias, '='))) {
1136 strndupx(xalias, alias, val++ - alias, ATEMP);
1140 if (val == NULL && !tflag && !xflag) {
1141 ap = ktsearch(t, alias, h);
1142 if (ap != NULL && (ap->flag&ISSET)) {
1144 shprintf("%s ", Talias);
1145 shf_puts(ap->name, shl_stdout);
1146 if (prefix != '+') {
1147 shf_putc('=', shl_stdout);
1148 print_value_quoted(shl_stdout, ap->val.s);
1150 shf_putc('\n', shl_stdout);
1152 shprintf("%s %s %s\n", alias, Talias,
1158 ap = ktenter(t, alias, h);
1159 ap->type = tflag ? CTALIAS : CALIAS;
1160 /* Are we setting the value or just some flags? */
1161 if ((val && !tflag) || (!val && tflag && !Uflag)) {
1162 if (ap->flag&ALLOC) {
1163 ap->flag &= ~(ALLOC|ISSET);
1164 afree(ap->val.s, APERM);
1166 /* ignore values for -t (AT&T ksh does this) */
1168 search_path(alias, path, X_OK, NULL) :
1171 strdupx(ap->val.s, newval, APERM);
1172 ap->flag |= ALLOC|ISSET;
1176 ap->flag |= DEFINED;
1181 afree(xalias, ATEMP);
1188 c_unalias(const char **wp)
1190 struct table *t = &aliases;
1195 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
1202 /* fix "unalias -dt" */
1218 wp += builtin_opt.optind;
1220 for (; *wp != NULL; wp++) {
1221 ap = ktsearch(t, *wp, hash(*wp));
1227 if (ap->flag&ALLOC) {
1228 ap->flag &= ~(ALLOC|ISSET);
1229 afree(ap->val.s, APERM);
1231 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1237 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
1238 if (ap->flag&ALLOC) {
1239 ap->flag &= ~(ALLOC|ISSET);
1240 afree(ap->val.s, APERM);
1242 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1250 c_let(const char **wp)
1256 /* AT&T ksh does this */
1257 bi_errorf("no arguments");
1259 for (wp++; *wp; wp++)
1260 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
1261 /* distinguish error from zero result */
1270 c_jobs(const char **wp)
1272 int optc, flag = 0, nflag = 0, rv = 0;
1274 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1286 /* debugging: print zombies */
1292 wp += builtin_opt.optind;
1294 if (j_jobs(NULL, flag, nflag))
1298 if (j_jobs(*wp, flag, nflag))
1304 #ifndef MKSH_UNEMPLOYED
1306 c_fgbg(const char **wp)
1308 bool bg = strcmp(*wp, "bg") == 0;
1311 if (!Flag(FMONITOR)) {
1312 bi_errorf("job control not enabled");
1315 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1317 wp += builtin_opt.optind;
1320 rv = j_resume(*wp, bg);
1322 rv = j_resume("%%", bg);
1323 /* fg returns $? of the job unless POSIX */
1324 return ((bg | Flag(FPOSIX)) ? 0 : rv);
1328 /* format a single kill item */
1330 kill_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1332 const struct kill_info *ki = (const struct kill_info *)arg;
1335 shf_snprintf(buf, buflen, "%*u %*s %s",
1337 ki->name_width, sigtraps[i].name,
1342 c_kill(const char **wp)
1349 /* assume old style options if -digits or -UPPERCASE */
1350 if ((p = wp[1]) && *p == '-' && (ksh_isdigit(p[1]) ||
1351 ksh_isupper(p[1]))) {
1352 if (!(t = gettrap(p + 1, false, false))) {
1353 bi_errorf("bad signal '%s'", p + 1);
1356 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1360 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1366 if (!(t = gettrap(builtin_opt.optarg,
1368 bi_errorf("bad signal '%s'",
1369 builtin_opt.optarg);
1376 i = builtin_opt.optind;
1378 if ((lflag && t) || (!wp[i] && !lflag)) {
1380 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1381 " { job | pid | pgrp } ...\n"
1382 "\tkill -l [exit_status ...]\n", shl_out);
1390 for (; wp[i]; i++) {
1391 if (!bi_getn(wp[i], &n))
1393 #if (ksh_NSIG <= 128)
1394 if (n > 128 && n < 128 + ksh_NSIG)
1397 if (n > 0 && n < ksh_NSIG)
1398 shprintf("%s\n", sigtraps[n].name);
1400 shprintf("%d\n", n);
1402 } else if (Flag(FPOSIX)) {
1404 while (n < ksh_NSIG) {
1405 shf_puts(sigtraps[n].name, shl_stdout);
1406 shf_putc(++n == ksh_NSIG ? '\n' : ' ',
1410 ssize_t w, mess_cols = 0, mess_octs = 0;
1411 int j = ksh_NSIG - 1;
1412 struct kill_info ki = { 0, 0 };
1416 } while ((j /= 10));
1418 for (j = 1; j < ksh_NSIG; j++) {
1419 w = strlen(sigtraps[j].name);
1420 if (w > ki.name_width)
1422 w = strlen(sigtraps[j].mess);
1425 w = utf_mbswidth(sigtraps[j].mess);
1430 print_columns(shl_stdout, (unsigned int)(ksh_NSIG - 1),
1431 kill_fmt_entry, (void *)&ki,
1432 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1433 ki.num_width + 1 + ki.name_width + 1 + mess_cols,
1439 sig = t ? t->signal : SIGTERM;
1440 for (; (p = wp[i]); i++) {
1444 } else if (!getn(p, &n)) {
1445 bi_errorf("%s: %s", p,
1446 "arguments must be jobs or process IDs");
1449 if (mksh_kill(n, sig) < 0) {
1450 bi_errorf("%s: %s", p, cstrerror(errno));
1459 getopts_reset(int val)
1462 ksh_getopt_reset(&user_opt, GF_NONAME |
1463 (Flag(FPOSIX) ? 0 : GF_PLUSOPT));
1464 user_opt.optind = user_opt.uoptind = val;
1469 c_getopts(const char **wp)
1472 const char *opts, *var;
1474 struct tbl *vq, *voptarg;
1476 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1478 wp += builtin_opt.optind;
1482 bi_errorf("missing %s argument", "options");
1488 bi_errorf("missing %s argument", "name");
1491 if (!*var || *skip_varname(var, true)) {
1492 bi_errorf("%s: %s", var, "is not an identifier");
1496 if (e->loc->next == NULL) {
1497 internal_warningf("%s: %s", "c_getopts", "no argv");
1500 /* Which arguments are we parsing... */
1502 wp = e->loc->next->argv;
1504 *--wp = e->loc->next->argv[0];
1506 /* Check that our saved state won't cause a core dump... */
1507 for (argc = 0; wp[argc]; argc++)
1509 if (user_opt.optind > argc ||
1511 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1512 bi_errorf("arguments changed since last call");
1516 user_opt.optarg = NULL;
1517 optc = ksh_getopt(wp, &user_opt, opts);
1519 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1525 * POSIX says var is set to ? at end-of-options, AT&T ksh
1526 * sets it to null - we go with POSIX...
1528 buf[0] = optc < 0 ? '?' : optc;
1532 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1533 user_opt.uoptind = user_opt.optind;
1535 voptarg = global("OPTARG");
1536 /* AT&T ksh clears ro and int */
1537 voptarg->flag &= ~RDONLY;
1538 /* Paranoia: ensure no bizarre results. */
1539 if (voptarg->flag & INTEGER)
1540 typeset("OPTARG", 0, INTEGER, 0, 0);
1541 if (user_opt.optarg == NULL)
1544 /* This can't fail (have cleared readonly/integer) */
1545 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1550 /* Error message already printed (integer, readonly) */
1551 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1554 typeset(var, EXPORT, 0, 0, 0);
1556 return (optc < 0 ? 1 : rv);
1559 #ifndef MKSH_NO_CMDLINE_EDITING
1561 c_bind(const char **wp)
1571 while ((optc = ksh_getopt(wp, &builtin_opt,
1590 wp += builtin_opt.optind;
1594 rv = x_bind(NULL, NULL,
1600 for (; *wp != NULL; wp++) {
1601 if ((cp = cstrchr(*wp, '=')) == NULL)
1604 strdupx(up, *wp, ATEMP);
1605 up[cp++ - *wp] = '\0';
1607 if (x_bind(up ? up : *wp, cp,
1621 c_shift(const char **wp)
1623 struct block *l = e->loc;
1628 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1630 arg = wp[builtin_opt.optind];
1634 else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
1635 /* error already printed */
1638 } else if (!(n = val)) {
1642 bi_errorf("%s: %s", arg, "bad number");
1646 bi_errorf("nothing to shift");
1649 l->argv[n] = l->argv[0];
1656 c_umask(const char **wp)
1660 bool symbolic = false;
1663 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1671 cp = wp[builtin_opt.optind];
1673 old_umask = umask((mode_t)0);
1679 old_umask = ~old_umask;
1681 for (i = 0; i < 3; i++) {
1684 for (j = 0; j < 3; j++)
1685 if (old_umask & (1 << (8 - (3*i + j))))
1690 shprintf("%s\n", buf);
1692 shprintf("%#3.3o\n", (unsigned int)old_umask);
1696 if (ksh_isdigit(*cp)) {
1698 while (*cp >= ord('0') && *cp <= ord('7')) {
1699 new_umask = new_umask * 8 + ksh_numdig(*cp);
1703 bi_errorf("bad number");
1707 /* symbolic format */
1708 int positions, new_val;
1711 old_umask = umask((mode_t)0);
1712 /* in case of error */
1714 old_umask = ~old_umask;
1715 new_umask = old_umask;
1718 while (*cp && vstrchr("augo", *cp))
1736 if (!vstrchr("=+-", op = *cp))
1740 while (*cp && vstrchr("rwxugoXs", *cp))
1742 case 'r': new_val |= 04; break;
1743 case 'w': new_val |= 02; break;
1744 case 'x': new_val |= 01; break;
1746 new_val |= old_umask >> 6;
1749 new_val |= old_umask >> 3;
1752 new_val |= old_umask >> 0;
1755 if (old_umask & 0111)
1762 new_val = (new_val & 07) * positions;
1765 new_umask &= ~new_val;
1768 new_umask = new_val |
1769 (new_umask & ~(positions * 07));
1772 new_umask |= new_val;
1777 } else if (!vstrchr("=+-", *cp))
1781 bi_errorf("bad mask");
1784 new_umask = ~new_umask;
1792 c_dot(const char **wp)
1794 const char *file, *cp, **argv;
1795 int argc, i, errcode;
1797 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1800 if ((cp = wp[builtin_opt.optind]) == NULL) {
1801 bi_errorf("missing argument");
1804 file = search_path(cp, path, R_OK, &errcode);
1805 if (!file && errcode == ENOENT && wp[0][0] == 's' &&
1806 search_access(cp, R_OK) == 0)
1809 bi_errorf("%s: %s", cp, cstrerror(errcode));
1813 /* Set positional parameters? */
1814 if (wp[builtin_opt.optind + 1]) {
1815 argv = wp + builtin_opt.optind;
1817 argv[0] = e->loc->argv[0];
1818 for (argc = 0; argv[argc + 1]; argc++)
1824 if ((i = include(file, argc, argv, false)) < 0) {
1825 /* should not happen */
1826 bi_errorf("%s: %s", cp, cstrerror(errno));
1833 c_wait(const char **wp)
1837 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1839 wp += builtin_opt.optind;
1841 while (waitfor(NULL, &sig) >= 0)
1846 rv = waitfor(*wp, &sig);
1848 /* magic exit code: bad job-id */
1849 rv = sig ? sig : 127;
1854 static char REPLY[] = "REPLY";
1856 c_read(const char **wp)
1858 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1859 int c, fd = 0, rv = 0;
1860 bool savehist = false, intoarray = false, aschars = false;
1861 bool rawmode = false, expanding = false;
1862 bool lastparmmode = false, lastparmused = false;
1863 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1865 size_t bytesleft = 128, bytesread;
1866 struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
1867 char *cp, *allocd = NULL, *xp;
1872 bool restore_tios = false;
1873 /* to catch read -aN2 foo[i] */
1874 bool subarray = false;
1876 bool hastimeout = false;
1877 struct timeval tv, tvlim;
1878 #define c_read_opts "Aad:N:n:prst:u,"
1880 #define c_read_opts "Aad:N:n:prsu,"
1883 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1892 delim = builtin_opt.optarg[0];
1896 readmode = c == 'N' ? BYTES : UPTO;
1897 if (!bi_getn(builtin_opt.optarg, &c))
1900 readmode = readmode == BYTES ? READALL : UPTO;
1903 bytesleft = (unsigned int)c;
1906 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1907 bi_errorf("%s: %s", "-p", ccp);
1919 if (parse_usec(builtin_opt.optarg, &tv)) {
1920 bi_errorf("%s: %s '%s'", Tsynerr, cstrerror(errno),
1921 builtin_opt.optarg);
1928 if (!builtin_opt.optarg[0])
1930 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1931 bi_errorf("%s: %s: %s", "-u", builtin_opt.optarg, ccp);
1938 wp += builtin_opt.optind;
1942 if (intoarray && wp[1] != NULL) {
1943 bi_errorf("too many arguments");
1947 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1948 strdupx(allocd, *wp, ATEMP);
1949 allocd[ccp - *wp] = '\0';
1953 * AT&T ksh says it prints prompt on fd if it's open
1954 * for writing and is a tty, but it doesn't do it
1955 * (it also doesn't check the interactive flag,
1956 * as is indicated in the Korn Shell book).
1958 shf_puts(ccp + 1, shl_out);
1963 Xinit(xs, xp, bytesleft, ATEMP);
1965 if (readmode == LINES)
1967 else if (isatty(fd)) {
1968 x_mkraw(fd, &tios, true);
1969 restore_tios = true;
1975 timeradd(&tvlim, &tv, &tvlim);
1985 FD_SET((unsigned int)fd, &fdset);
1987 timersub(&tvlim, &tv, &tv);
1988 if (tv.tv_sec < 0) {
1989 /* timeout expired globally */
1994 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
1998 /* timeout expired for this call */
2000 /* fake EOF read; all cases return 1 */
2001 goto c_read_didread;
2003 bi_errorf("%s: %s", Tselect, cstrerror(errno));
2010 bytesread = blocking_read(fd, xp, bytesleft);
2011 if (bytesread == (size_t)-1) {
2013 if (errno == EINTR && fatal_trap_check()) {
2015 * Was the offending signal one that would
2016 * normally kill a process? If so, pretend
2017 * the read was killed.
2022 /* just ignore the signal */
2023 goto c_read_readloop;
2029 if (bytesread == 0) {
2030 /* end of file reached */
2032 goto c_read_readdone;
2035 XcheckN(xs, xp, bytesleft);
2040 /* end of file reached */
2043 goto c_read_readdone;
2046 if (bytesread == 0) {
2047 /* end of file reached */
2049 /* may be partial read: $? = 1, but content */
2050 goto c_read_readdone;
2053 if ((bytesleft -= bytesread) == 0)
2054 goto c_read_readdone;
2057 if (bytesread == 0) {
2058 /* end of file reached */
2060 goto c_read_readdone;
2062 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
2063 /* skip any read NULs unless delimiter */
2069 if (Flag(FTALKING_I) && isatty(fd)) {
2071 * set prompt in case this is
2072 * called from .profile or $ENV
2074 set_prompt(PS2, NULL);
2077 /* drop the backslash */
2079 /* and the delimiter */
2082 } else if (c == delim) {
2083 goto c_read_readdone;
2084 } else if (!rawmode && c == '\\') {
2091 goto c_read_readloop;
2094 bytesread = Xlength(xs, xp);
2098 * state: we finished reading the input and NUL terminated it
2099 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
2100 * rv = 1 if EOF, 0 otherwise (errors handled already)
2104 /* clean up coprocess if needed, on EOF */
2105 coproc_read_close(fd);
2106 if (readmode == READALL)
2107 /* EOF is no error here */
2112 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
2114 ccp = cp = Xclose(xs, xp);
2116 XinitN(xs, 128, ATEMP);
2119 subarray = last_lookup_was_array;
2120 if (vp->flag & RDONLY) {
2122 bi_errorf("read-only: %s", *wp);
2128 /* counter for array index */
2129 c = subarray ? arrayindex(vp) : 0;
2130 /* exporting an array is currently pointless */
2131 unset(vp, subarray ? 0 : 1);
2134 /* skip initial IFS whitespace */
2135 while (bytesread && is_ifsws(*ccp)) {
2139 /* trim trailing IFS whitespace */
2140 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
2145 xp = Xstring(xs, xp);
2146 /* generate next word */
2150 goto c_read_splitdone;
2151 /* zero out next parameters */
2152 goto c_read_gotword;
2157 bytesleft = utf_ptradj(ccp);
2158 while (bytesleft && bytesread) {
2163 if (xp[-1] == '\0') {
2167 goto c_read_gotword;
2170 if (!intoarray && wp[1] == NULL)
2171 lastparmmode = true;
2174 /* copy until IFS character */
2181 goto c_read_splitcopy;
2182 } else if (ctype(ch, C_IFS)) {
2184 } else if (!rawmode && ch == '\\') {
2194 xsave = Xsavepos(xs, xp);
2195 /* copy word delimiter: IFSWS+IFS,IFSWS */
2201 if (!ctype(ch, C_IFS))
2203 if (lastparmmode && !expanding && !rawmode && ch == '\\') {
2213 if (!ctype(ch, C_IFSWS))
2216 while (bytesread && is_ifsws(*ccp)) {
2222 /* if no more parameters, rinse and repeat */
2223 if (lastparmmode && bytesread) {
2224 lastparmused = true;
2225 goto c_read_splitlast;
2227 /* get rid of the delimiter unless we pack the rest */
2229 xp = Xrestpos(xs, xp, xsave);
2234 /* array element passed, accept first read */
2236 bi_errorf("nested arrays not yet supported");
2237 goto c_read_spliterr;
2244 vq = arraysearch(vp, c++);
2247 /* must be checked before exporting */
2248 if (vq->flag & RDONLY)
2249 goto c_read_splitro;
2251 typeset(*wp, EXPORT, 0, 0, 0);
2253 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
2254 goto c_read_spliterr;
2256 setint_v(vq, vq, false);
2257 /* protect from UTFMODE changes */
2260 if (intoarray || *++wp != NULL)
2261 goto c_read_splitloop;
2268 afree(allocd, ATEMP);
2271 mksh_tcset(fd, &tios);
2277 c_eval(const char **wp)
2279 struct source *s, *saves = source;
2280 unsigned char savef;
2283 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2285 s = pushs(SWORDS, ATEMP);
2286 s->u.strv = wp + builtin_opt.optind;
2289 * The following code handles the case where the command is
2290 * empty due to failed command substitution, for example by
2292 * This has historically returned 1 by AT&T ksh88. In this
2293 * case, shell() will not set or change exstat because the
2294 * compiled tree is empty, so it will use the value we pass
2295 * from subst_exstat, which is cleared in execute(), so it
2296 * should have been 0 if there were no substitutions.
2298 * POSIX however says we don't do this, even though it is
2299 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2300 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2302 * 2.9.1: Simple Commands
2303 * ... If there is a command name, execution shall
2304 * continue as described in 2.9.1.1 [Command Search
2305 * and Execution]. If there is no command name, but
2306 * the command contained a command substitution, the
2307 * command shall complete with the exit status of the
2308 * last command substitution performed.
2309 * 2.9.1.1: Command Search and Execution
2310 * (1) a. If the command name matches the name of a
2311 * special built-in utility, that special built-in
2312 * utility shall be invoked.
2314 * If there are no arguments, or only null arguments,
2315 * eval shall return a zero exit status; ...
2317 /* AT&T ksh88: use subst_exstat */
2318 /* exstat = subst_exstat; */
2319 /* SUSv4: OR with a high value never written otherwise */
2322 savef = Flag(FERREXIT);
2323 Flag(FERREXIT) |= 0x80;
2324 rv = shell(s, false);
2325 Flag(FERREXIT) = savef;
2328 if (exstat & 0x4000)
2329 /* detect old exstat, use 0 in that case */
2335 c_trap(const char **wp)
2341 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2343 wp += builtin_opt.optind;
2348 shf_puts("trap -- ", shl_stdout);
2349 print_value_quoted(shl_stdout, p->trap);
2350 shprintf(" %s\n", p->name);
2357 if (getn(*wp, &i)) {
2358 /* first argument is a signal number, reset them all */
2361 /* first argument must be a command, then */
2368 /* set/clear the traps */
2371 if (!(p = gettrap(*wp++, true, true))) {
2372 warningf(true, "%s: %s '%s'", builtin_argv0,
2373 "bad signal", wp[-1]);
2381 c_exitreturn(const char **wp)
2387 goto c_exitreturn_err;
2388 exstat = bi_getn(wp[1], &n) ? (n & 0xFF) : 1;
2389 } else if (trap_exstat != -1)
2390 exstat = trap_exstat;
2392 if (wp[0][0] == 'r') {
2397 * need to tell if this is exit or return so trap exit will
2398 * work right (POSIX)
2400 for (ep = e; ep; ep = ep->oenv)
2401 if (STOP_RETURN(ep->type)) {
2407 if (how == LEXIT && !really_exit && j_stopped_running()) {
2412 /* get rid of any I/O redirections */
2418 bi_errorf("too many arguments");
2423 c_brkcont(const char **wp)
2427 struct env *ep, *last_ep = NULL;
2430 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2432 arg = wp[builtin_opt.optind];
2436 else if (!bi_getn(arg, &n))
2439 /* AT&T ksh does this for non-interactive shells only - weird */
2440 bi_errorf("%s: %s", arg, "bad value");
2443 quit = (unsigned int)n;
2445 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2446 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2447 if (ep->type == E_LOOP) {
2450 ep->flags |= EF_BRKCONT_PASS;
2456 * AT&T ksh doesn't print a message - just does what it
2457 * can. We print a message 'cause it helps in debugging
2458 * scripts, but don't generate an error (ie, keep going).
2460 if ((unsigned int)n == quit) {
2461 warningf(true, "%s: %s %s", wp[0], "can't", wp[0]);
2465 * POSIX says if n is too big, the last enclosing loop
2466 * shall be used. Doesn't say to print an error but we
2467 * do anyway 'cause the user messed up.
2470 last_ep->flags &= ~EF_BRKCONT_PASS;
2471 warningf(true, "%s: can only %s %u level(s)",
2472 wp[0], wp[0], (unsigned int)n - quit);
2475 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2483 c_set(const char **wp)
2487 struct block *l = e->loc;
2490 if (wp[1] == NULL) {
2491 static const char *args[] = { Tset, "-", NULL };
2492 return (c_typeset(args));
2495 if ((argi = parse_args(wp, OF_SET, &setargs)) < 0)
2503 while (*++wp != NULL)
2504 strdupx(*wp, *wp, &l->area);
2505 l->argc = wp - owp - 1;
2506 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2507 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2511 * POSIX says set exit status is 0, but old scripts that use
2512 * getopt(1) use the construct
2513 * set -- $(getopt ab:c "$@")
2514 * which assumes the exit value set will be that of the $()
2515 * (subst_exstat is cleared in execute() so that it will be 0
2516 * if there are no command substitutions).
2518 #ifdef MKSH_LEGACY_MODE
2519 /* traditional behaviour, unless set -o posix */
2520 return (Flag(FPOSIX) ? 0 : subst_exstat);
2522 /* conformant behaviour, unless set -o sh +o posix */
2523 return (Flag(FSH) && !Flag(FPOSIX) ? subst_exstat : 0);
2528 c_unset(const char **wp)
2532 bool unset_var = true;
2534 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2543 /*XXX not reached due to GF_ERROR */
2546 wp += builtin_opt.optind;
2547 for (; (id = *wp) != NULL; wp++)
2549 /* unset variable */
2555 if (n > 3 && id[n-3] == '[' && id[n-2] == '*' &&
2557 strndupx(cp, id, n - 3, ATEMP);
2561 optc = vstrchr(id, '[') ? 0 : 1;
2566 if ((vp->flag&RDONLY)) {
2567 warningf(true, "read-only: %s", vp->name);
2572 /* unset function */
2578 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2579 const char *prefix, const char *suffix)
2583 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2584 tv_sec, tv_usec, suffix);
2586 shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
2587 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2591 c_times(const char **wp MKSH_A_UNUSED)
2593 struct rusage usage;
2595 getrusage(RUSAGE_SELF, &usage);
2596 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2597 usage.ru_utime.tv_usec, 0, null, " ");
2598 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2599 usage.ru_stime.tv_usec, 0, null, "\n");
2601 getrusage(RUSAGE_CHILDREN, &usage);
2602 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2603 usage.ru_utime.tv_usec, 0, null, " ");
2604 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2605 usage.ru_stime.tv_usec, 0, null, "\n");
2611 * time pipeline (really a statement, not a built-in command)
2614 timex(struct op *t, int f, volatile int *xerrok)
2616 #define TF_NOARGS BIT(0)
2617 #define TF_NOREAL BIT(1) /* don't report real time */
2618 #define TF_POSIX BIT(2) /* report in POSIX format */
2620 struct rusage ru0, ru1, cru0, cru1;
2621 struct timeval usrtime, systime, tv0, tv1;
2624 getrusage(RUSAGE_SELF, &ru0);
2625 getrusage(RUSAGE_CHILDREN, &cru0);
2628 * Two ways of getting cpu usage of a command: just use t0
2629 * and t1 (which will get cpu usage from other jobs that
2630 * finish while we are executing t->left), or get the
2631 * cpu usage of t->left. AT&T ksh does the former, while
2632 * pdksh tries to do the later (the j_usrtime hack doesn't
2633 * really work as it only counts the last job).
2635 timerclear(&j_usrtime);
2636 timerclear(&j_systime);
2637 rv = execute(t->left, f | XTIME, xerrok);
2638 if (t->left->type == TCOM)
2639 tf |= t->left->str[0];
2641 getrusage(RUSAGE_SELF, &ru1);
2642 getrusage(RUSAGE_CHILDREN, &cru1);
2646 if (tf & TF_NOARGS) {
2647 /* ksh93 - report shell times (shell+kids) */
2649 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2650 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2652 timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
2653 timeradd(&usrtime, &j_usrtime, &usrtime);
2654 timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
2655 timeradd(&systime, &j_systime, &systime);
2658 if (!(tf & TF_NOREAL)) {
2659 timersub(&tv1, &tv0, &tv1);
2661 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2664 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2668 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2671 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2674 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2677 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2678 5, null, " system\n");
2685 timex_hook(struct op *t, char **volatile *app)
2691 ksh_getopt_reset(&opt, 0);
2692 /* start at the start */
2694 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2697 t->str[0] |= TF_POSIX;
2700 errorf("time: -%s %s", opt.optarg,
2703 errorf("time: -%s %s", opt.optarg,
2704 "requires an argument");
2706 /* Copy command words down over options. */
2707 if (opt.optind != 0) {
2708 for (i = 0; i < opt.optind; i++)
2709 afree(wp[i], ATEMP);
2710 for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
2714 t->str[0] |= TF_NOARGS;
2718 /* exec with no args - args case is taken care of in comexec() */
2720 c_exec(const char **wp MKSH_A_UNUSED)
2724 /* make sure redirects stay in place */
2725 if (e->savefd != NULL) {
2726 for (i = 0; i < NUFILE; i++) {
2727 if (e->savefd[i] > 0)
2728 close(e->savefd[i]);
2729 #ifndef MKSH_LEGACY_MODE
2731 * keep all file descriptors > 2 private for ksh,
2732 * but not for POSIX or legacy/kludge sh
2734 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2736 fcntl(i, F_SETFD, FD_CLOEXEC);
2746 c_mknod(const char **wp)
2748 int argc, optc, rv = 0;
2749 bool ismkfifo = false;
2752 mode_t mode = 0, oldmode = 0;
2754 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2757 set = setmode(builtin_opt.optarg);
2759 bi_errorf("invalid file mode");
2762 mode = getmode(set, (mode_t)(DEFFILEMODE));
2763 free_ossetmode(set);
2769 argv = &wp[builtin_opt.optind];
2770 if (argv[0] == NULL)
2772 for (argc = 0; argv[argc]; argc++)
2774 if (argc == 2 && argv[1][0] == 'p')
2776 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2780 oldmode = umask((mode_t)0);
2784 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2785 (argv[1][0] == 'c') ? S_IFCHR : 0;
2788 unsigned long majnum, minnum;
2792 majnum = strtoul(argv[2], &c, 0);
2793 if ((c == argv[2]) || (*c != '\0')) {
2794 bi_errorf("non-numeric %s %s '%s'", "device", "major", argv[2]);
2797 minnum = strtoul(argv[3], &c, 0);
2798 if ((c == argv[3]) || (*c != '\0')) {
2799 bi_errorf("non-numeric %s %s '%s'", "device", "minor", argv[3]);
2802 dv = makedev(majnum, minnum);
2803 if ((unsigned long)(major(dv)) != majnum) {
2804 bi_errorf("%s %s too large: %lu", "device", "major", majnum);
2807 if ((unsigned long)(minor(dv)) != minnum) {
2808 bi_errorf("%s %s too large: %lu", "device", "minor", minnum);
2811 if (mknod(argv[0], mode, dv))
2812 goto c_mknod_failed;
2813 } else if (mkfifo(argv[0], mode)) {
2815 bi_errorf("%s: %s", argv[0], cstrerror(errno));
2824 bi_errorf("%s: %s", "usage", "mknod [-m mode] name b|c major minor");
2825 bi_errorf("%s: %s", "usage", "mknod [-m mode] name p");
2831 test(1) roughly accepts the following grammar:
2832 oexpr ::= aexpr | aexpr "-o" oexpr ;
2833 aexpr ::= nexpr | nexpr "-a" aexpr ;
2834 nexpr ::= primary | "!" nexpr ;
2835 primary ::= unary-operator operand
2836 | operand binary-operator operand
2841 unary-operator ::= "-a"|"-r"|"-w"|"-x"|"-e"|"-f"|"-d"|"-c"|"-b"|"-p"|
2842 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|
2843 "-L"|"-h"|"-S"|"-H";
2845 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
2847 "<"|">" # rules used for [[ ... ]] expressions
2849 operand ::= <anything>
2852 /* POSIX says > 1 for errors */
2853 #define T_ERR_EXIT 2
2856 c_test(const char **wp)
2858 int argc, rv, invert = 0;
2861 const char *lhs, **swp;
2865 te.getopnd = ptest_getopnd;
2866 te.eval = test_eval;
2867 te.error = ptest_error;
2869 for (argc = 0; wp[argc]; argc++)
2872 if (strcmp(wp[0], "[") == 0) {
2873 if (strcmp(wp[--argc], "]") != 0) {
2874 bi_errorf("missing ]");
2875 return (T_ERR_EXIT);
2880 te.wp_end = wp + argc;
2883 * Attempt to conform to POSIX special cases. This is pretty
2884 * dumb code straight-forward from the 2008 spec, but unlike
2885 * the old pdksh code doesn't live from so many assumptions.
2886 * It does, though, inline some calls to '(*te.funcname)()'.
2897 if (ptest_isa(&te, TM_NOT)) {
2901 if ((op = ptest_isa(&te, TM_UNOP))) {
2903 rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
2905 if (te.flags & TEF_ERROR)
2906 return (T_ERR_EXIT);
2907 return ((invert & 1) ? rv : !rv);
2909 /* let the parser deal with anything else */
2914 /* use inside knowledge of ptest_getopnd inlined below */
2916 if ((op = ptest_isa(&te, TM_BINOP))) {
2917 /* test lhs op rhs */
2918 rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
2921 /* back up to lhs */
2923 if (ptest_isa(&te, TM_NOT)) {
2927 if (ptest_isa(&te, TM_OPAREN)) {
2929 /* skip operand, without evaluation */
2931 /* check for closing parenthesis */
2932 op = ptest_isa(&te, TM_CPAREN);
2933 /* back up to operand */
2935 /* if there was a closing paren, handle it */
2938 /* backing up is done before calling the parser */
2940 /* let the parser deal with it */
2943 if (ptest_isa(&te, TM_NOT)) {
2947 if (ptest_isa(&te, TM_OPAREN)) {
2949 /* skip two operands, without evaluation */
2952 /* check for closing parenthesis */
2953 op = ptest_isa(&te, TM_CPAREN);
2954 /* back up to first operand */
2956 /* if there was a closing paren, handle it */
2959 /* backing up is done before calling the parser */
2961 /* defer this to the parser */
2965 /* "The results are unspecified." */
2967 return (test_parse(&te));
2971 * Generic test routines.
2975 test_isop(Test_meta meta, const char *s)
2978 const struct t_op *tbl;
2980 tbl = meta == TM_UNOP ? u_ops : b_ops;
2983 for (; tbl->op_text[0]; tbl++)
2984 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
2985 return (tbl->op_num);
2991 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
3004 /* Binary operators */
3018 /* consistency check, but does not happen in practice */
3020 te->flags |= TEF_ERROR;
3025 /* for completeness of switch */
3038 return (*opnd1 != '\0');
3042 return (*opnd1 == '\0');
3046 if ((i = *opnd1) == '!' || i == '?')
3048 if ((k = option(opnd1)) == (size_t)-1)
3050 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
3054 /* LINTED use of access */
3055 return (access(opnd1, R_OK) == 0);
3059 /* LINTED use of access */
3060 return (access(opnd1, W_OK) == 0);
3064 return (ksh_access(opnd1, X_OK) == 0);
3070 return (stat(opnd1, &b1) == 0);
3074 return (stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
3078 return (stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
3082 return (stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
3086 return (stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
3090 return (stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
3094 #ifdef MKSH__NO_SYMLINK
3097 return (lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
3102 return (stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
3104 /* -H => HP context dependent files (directories) */
3111 * Append a + to filename and check to see if result is
3112 * a setuid directory. CDF stuff in general is hookey,
3113 * since it breaks for, e.g., the following sequence:
3114 * echo hi >foo+; mkdir foo; echo bye >foo/default;
3115 * chmod u+s foo (foo+ refers to the file with hi in it,
3116 * there is no way to get at the file with bye in it;
3117 * please correct me if I'm wrong about this).
3120 nv = shf_smprintf("%s+", opnd1);
3121 i = (stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
3131 return (stat(opnd1, &b1) == 0 &&
3132 (b1.st_mode & S_ISUID) == S_ISUID);
3136 return (stat(opnd1, &b1) == 0 &&
3137 (b1.st_mode & S_ISGID) == S_ISGID);
3142 return (stat(opnd1, &b1) == 0 &&
3143 (b1.st_mode & S_ISVTX) == S_ISVTX);
3150 return (stat(opnd1, &b1) == 0 && (off_t)b1.st_size > (off_t)0);
3154 if (opnd1 && !bi_getn(opnd1, &i)) {
3155 te->flags |= TEF_ERROR;
3158 i = isatty(opnd1 ? i : 0);
3163 return (stat(opnd1, &b1) == 0 && (uid_t)b1.st_uid == ksheuid);
3167 return (stat(opnd1, &b1) == 0 && (gid_t)b1.st_gid == getegid());
3175 if (te->flags & TEF_DBRACKET)
3176 return (gmatchx(opnd1, opnd2, false));
3177 return (strcmp(opnd1, opnd2) == 0);
3181 if (te->flags & TEF_DBRACKET)
3182 return (!gmatchx(opnd1, opnd2, false));
3183 return (strcmp(opnd1, opnd2) != 0);
3187 return (strcmp(opnd1, opnd2) < 0);
3191 return (strcmp(opnd1, opnd2) > 0);
3205 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
3206 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
3207 /* error already printed.. */
3208 te->flags |= TEF_ERROR;
3233 * ksh88/ksh93 succeed if file2 can't be stated
3234 * (subtly different from 'does not exist').
3236 return (stat(opnd1, &b1) == 0 &&
3237 (((s = stat(opnd2, &b2)) == 0 &&
3238 b1.st_mtime > b2.st_mtime) || s < 0));
3243 * ksh88/ksh93 succeed if file1 can't be stated
3244 * (subtly different from 'does not exist').
3246 return (stat(opnd2, &b2) == 0 &&
3247 (((s = stat(opnd1, &b1)) == 0 &&
3248 b1.st_mtime < b2.st_mtime) || s < 0));
3252 return (stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0 &&
3253 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
3255 /* all other cases */
3258 /* throw the error */
3261 (*te->error)(te, 0, "internal error: unknown op");
3266 test_parse(Test_env *te)
3270 rv = test_oexpr(te, 1);
3272 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3273 (*te->error)(te, 0, "unexpected operator/operand");
3275 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3279 test_oexpr(Test_env *te, bool do_eval)
3283 if ((rv = test_aexpr(te, do_eval)))
3285 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3286 return (test_oexpr(te, do_eval) || rv);
3291 test_aexpr(Test_env *te, bool do_eval)
3295 if (!(rv = test_nexpr(te, do_eval)))
3297 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3298 return (test_aexpr(te, do_eval) && rv);
3303 test_nexpr(Test_env *te, bool do_eval)
3305 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3306 return (!test_nexpr(te, do_eval));
3307 return (test_primary(te, do_eval));
3311 test_primary(Test_env *te, bool do_eval)
3313 const char *opnd1, *opnd2;
3317 if (te->flags & TEF_ERROR)
3319 if ((*te->isa)(te, TM_OPAREN)) {
3320 rv = test_oexpr(te, do_eval);
3321 if (te->flags & TEF_ERROR)
3323 if (!(*te->isa)(te, TM_CPAREN)) {
3324 (*te->error)(te, 0, "missing )");
3330 * Binary should have precedence over unary in this case
3331 * so that something like test \( -f = -f \) is accepted
3333 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3334 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3335 if ((op = (*te->isa)(te, TM_UNOP))) {
3336 /* unary expression */
3337 opnd1 = (*te->getopnd)(te, op, do_eval);
3339 (*te->error)(te, -1, "missing argument");
3343 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3346 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3348 (*te->error)(te, 0, "expression expected");
3351 if ((op = (*te->isa)(te, TM_BINOP))) {
3352 /* binary expression */
3353 opnd2 = (*te->getopnd)(te, op, do_eval);
3355 (*te->error)(te, -1, "missing second argument");
3359 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3361 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3365 * Plain test (test and [ .. ]) specific routines.
3369 * Test if the current token is a whatever. Accepts the current token if
3370 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3371 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3374 ptest_isa(Test_env *te, Test_meta meta)
3376 /* Order important - indexed by Test_meta values */
3377 static const char * const tokens[] = {
3378 "-o", "-a", "!", "(", ")"
3382 if (te->pos.wp >= te->wp_end)
3383 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3385 if (meta == TM_UNOP || meta == TM_BINOP)
3386 rv = test_isop(meta, *te->pos.wp);
3387 else if (meta == TM_END)
3390 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3391 TO_NONNULL : TO_NONOP;
3393 /* Accept the token? */
3401 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3403 if (te->pos.wp >= te->wp_end)
3404 return (op == TO_FILTT ? "1" : NULL);
3405 return (*te->pos.wp++);
3409 ptest_error(Test_env *te, int ofs, const char *msg)
3413 te->flags |= TEF_ERROR;
3414 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3415 bi_errorf("%s: %s", op, msg);
3417 bi_errorf("%s", msg);
3420 #ifndef MKSH_NO_LIMITS
3424 /* Magic to divine the 'm' and 'v' limits */
3427 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3428 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3429 #define ULIMIT_V_IS_AS
3430 #elif defined(RLIMIT_VMEM)
3431 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3432 #define ULIMIT_V_IS_AS
3434 #define ULIMIT_V_IS_VMEM
3440 #ifdef ULIMIT_V_IS_VMEM
3441 #define ULIMIT_M_IS_RSS
3442 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3443 #define ULIMIT_M_IS_VMEM
3445 #define ULIMIT_M_IS_RSS
3447 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3448 #undef ULIMIT_M_IS_RSS
3452 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3453 #define ULIMIT_V_IS_VMEM
3456 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3457 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3458 #define ULIMIT_M_IS_VMEM
3461 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3462 (RLIMIT_VMEM == RLIMIT_AS)
3463 #undef ULIMIT_M_IS_VMEM
3466 #if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
3467 # error nonsensical m ulimit
3470 #if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
3471 # error nonsensical v ulimit
3475 /* limit resource */
3477 /* multiply by to get rlim_{cur,max} values */
3478 unsigned int factor;
3485 #define RLIMITS_DEFNS
3486 #define FN(lname,lid,lfac,lopt) \
3487 static const struct { \
3489 unsigned int factor; \
3491 char name[sizeof(lname)]; \
3492 } rlimits_ ## lid = { \
3493 lid, lfac, lopt, lname \
3495 #include "rlimits.gen"
3497 static void print_ulimit(const struct limits *, int);
3498 static int set_ulimit(const struct limits *, const char *, int);
3500 static const struct limits * const rlimits[] = {
3501 #define RLIMITS_ITEMS
3502 #include "rlimits.gen"
3505 static const char rlimits_opts[] =
3506 #define RLIMITS_OPTCS
3507 #include "rlimits.gen"
3511 c_ulimit(const char **wp)
3514 int how = SOFT | HARD, optc, what = 'f';
3517 while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
3529 bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
3535 while (i < NELEM(rlimits)) {
3536 if (rlimits[i]->optchar == what)
3540 internal_warningf("ulimit: %c", what);
3543 if (wp[builtin_opt.optind]) {
3544 if (all || wp[builtin_opt.optind + 1]) {
3545 bi_errorf("too many arguments");
3548 return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
3551 print_ulimit(rlimits[i], how);
3552 else for (i = 0; i < NELEM(rlimits); ++i) {
3553 shprintf("%-20s ", rlimits[i]->name);
3554 print_ulimit(rlimits[i], how);
3560 set_ulimit(const struct limits *l, const char *v, int how)
3562 rlim_t val = (rlim_t)0;
3563 struct rlimit limit;
3565 if (strcmp(v, "unlimited") == 0)
3566 val = (rlim_t)RLIM_INFINITY;
3570 if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
3573 * Avoid problems caused by typos that evaluate misses due
3574 * to evaluating unset parameters to 0...
3575 * If this causes problems, will have to add parameter to
3576 * evaluate() to control if unset params are 0 or an error.
3578 if (!rval && !ksh_isdigit(v[0])) {
3579 bi_errorf("invalid %s limit: %s", l->name, v);
3582 val = (rlim_t)((rlim_t)rval * l->factor);
3585 if (getrlimit(l->resource, &limit) < 0) {
3587 bi_errorf("limit %s could not be read, contact the mksh developers: %s",
3588 l->name, cstrerror(errno));
3590 /* some can't be read */
3591 limit.rlim_cur = RLIM_INFINITY;
3592 limit.rlim_max = RLIM_INFINITY;
3595 limit.rlim_cur = val;
3597 limit.rlim_max = val;
3598 if (!setrlimit(l->resource, &limit))
3601 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3603 bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
3608 print_ulimit(const struct limits *l, int how)
3610 rlim_t val = (rlim_t)0;
3611 struct rlimit limit;
3613 if (getrlimit(l->resource, &limit)) {
3614 shf_puts("unknown\n", shl_stdout);
3618 val = limit.rlim_cur;
3619 else if (how & HARD)
3620 val = limit.rlim_max;
3621 if (val == (rlim_t)RLIM_INFINITY)
3622 shf_puts("unlimited\n", shl_stdout);
3624 shprintf("%lu\n", (unsigned long)(val / l->factor));
3629 c_rename(const char **wp)
3635 if (wp[0] && !strcmp(wp[0], "--"))
3636 /* skip "--" (options separator) */
3639 /* check for exactly two arguments */
3640 if (wp[0] == NULL /* first argument */ ||
3641 wp[1] == NULL /* second argument */ ||
3642 wp[2] != NULL /* no further args please */)
3644 else if ((rv = rename(wp[0], wp[1])) != 0) {
3646 bi_errorf("%s: %s", "failed", cstrerror(rv));
3653 c_realpath(const char **wp)
3660 if (wp[0] && !strcmp(wp[0], "--"))
3661 /* skip "--" (options separator) */
3664 /* check for exactly one argument */
3665 if (wp[0] == NULL || wp[1] != NULL)
3667 else if ((buf = do_realpath(wp[0])) == NULL) {
3669 bi_errorf("%s: %s", wp[0], cstrerror(rv));
3670 if ((unsigned int)rv > 255)
3673 shprintf("%s\n", buf);
3682 c_cat(const char **wp)
3684 int fd = STDIN_FILENO, rv;
3686 const char *fn = "<stdin>";
3689 #define MKSH_CAT_BUFSIZ 4096
3691 /* parse options: POSIX demands we support "-u" as no-op */
3692 while ((rv = ksh_getopt(wp, &builtin_opt, "u")) != -1) {
3695 /* we already operate unbuffered */
3702 wp += builtin_opt.optind;
3705 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3706 bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
3711 opipe = block_pipe();
3718 else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
3719 bi_errorf("%s: %s", fn, cstrerror(errno));
3724 while (/* CONSTCOND */ 1) {
3725 if ((n = blocking_read(fd, (cp = buf),
3726 MKSH_CAT_BUFSIZ)) == -1) {
3727 if (errno == EINTR) {
3728 restore_pipe(opipe);
3729 /* give the user a chance to ^C out */
3731 /* interrupted, try again */
3732 opipe = block_pipe();
3735 /* an error occured during reading */
3736 bi_errorf("%s: %s", fn, cstrerror(errno));
3740 /* end of file reached */
3743 if ((w = write(STDOUT_FILENO, cp, n)) != -1) {
3748 if (errno == EINTR) {
3749 restore_pipe(opipe);
3750 /* give the user a chance to ^C out */
3752 /* interrupted, try again */
3753 opipe = block_pipe();
3756 if (errno == EPIPE) {
3757 /* fake receiving signel */
3758 rv = ksh_sigmask(SIGPIPE);
3760 /* an error occured during writing */
3761 bi_errorf("%s: %s", "<stdout>",
3765 if (fd != STDIN_FILENO)
3770 if (fd != STDIN_FILENO)
3775 restore_pipe(opipe);
3782 c_sleep(const char **wp)
3789 if (wp[0] && !strcmp(wp[0], "--"))
3790 /* skip "--" (options separator) */
3793 if (!wp[0] || wp[1])
3795 else if (parse_usec(wp[0], &tv))
3796 bi_errorf("%s: %s '%s'", Tsynerr, cstrerror(errno), wp[0]);
3798 #ifndef MKSH_NOPROSPECTOFWORK
3799 sigset_t omask, bmask;
3801 /* block a number of signals from interrupting us, though */
3802 (void)sigemptyset(&bmask);
3803 (void)sigaddset(&bmask, SIGPIPE);
3804 (void)sigaddset(&bmask, SIGCHLD);
3806 (void)sigaddset(&bmask, SIGWINCH);
3809 (void)sigaddset(&bmask, SIGINFO);
3812 (void)sigaddset(&bmask, SIGUSR1);
3815 (void)sigaddset(&bmask, SIGUSR2);
3817 sigprocmask(SIG_BLOCK, &bmask, &omask);
3819 if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3821 * strictly speaking only for SIGALRM, but the
3822 * execution may be interrupted by other signals
3826 bi_errorf("%s: %s", Tselect, cstrerror(errno));
3827 #ifndef MKSH_NOPROSPECTOFWORK
3828 /* this will re-schedule signal delivery */
3829 sigprocmask(SIG_SETMASK, &omask, NULL);
3836 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
3838 c_suspend(const char **wp)
3840 if (wp[1] != NULL) {
3841 bi_errorf("too many arguments");
3845 /* Can't suspend an orphaned process group. */
3846 if (getpgid(kshppid) == getpgid(0) ||
3847 getsid(kshppid) != getsid(0)) {
3848 bi_errorf("can't suspend a login shell");