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.305 2016/08/01 21:38:02 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 static int do_whence(const char **, int, bool, bool);
69 /* getn() that prints error */
71 bi_getn(const char *as, int *ai)
75 if (!(rv = getn(as, ai)))
76 bi_errorf(Tf_sD_s, as, "bad number");
81 c_true(const char **wp MKSH_A_UNUSED)
87 c_false(const char **wp MKSH_A_UNUSED)
93 * A leading = means assignments before command are kept.
94 * A leading * means a POSIX special builtin.
96 const struct builtin mkshbuiltins[] = {
100 /* no =: AT&T manual wrong */
102 {"*=break", c_brkcont},
103 {Tgbuiltin, c_builtin},
106 /* dash compatibility hack */
108 {Tcommand, c_command},
109 {"*=continue", c_brkcont},
113 {"*=exit", c_exitreturn},
114 {Tsgexport, c_typeset},
117 {Tgetopts, c_getopts},
118 {"=global", c_typeset},
126 {Tsgreadonly, c_typeset},
127 {"!realpath", c_realpath},
128 {"~rename", c_rename},
129 {"*=return", c_exitreturn},
131 {"*=shift", c_shift},
133 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
134 {Tsuspend, c_suspend},
137 {"*=times", c_times},
140 {Tgtypeset, c_typeset},
141 {"ulimit", c_ulimit},
143 {Tunalias, c_unalias},
144 {"*=unset", c_unset},
146 {"whence", c_whence},
147 #ifndef MKSH_UNEMPLOYED
151 #ifndef MKSH_NO_CMDLINE_EDITING
157 #ifdef MKSH_PRINTF_BUILTIN
158 {"~printf", c_printf},
164 /* alias to "true" for historical reasons */
165 {"domainname", c_true},
170 {NULL, (int (*)(const char **))NULL}
178 static const struct t_op {
208 static const struct t_op b_ops[] = {
226 static int test_oexpr(Test_env *, bool);
227 static int test_aexpr(Test_env *, bool);
228 static int test_nexpr(Test_env *, bool);
229 static int test_primary(Test_env *, bool);
230 static Test_op ptest_isa(Test_env *, Test_meta);
231 static const char *ptest_getopnd(Test_env *, Test_op, bool);
232 static void ptest_error(Test_env *, int, const char *);
233 static void kill_fmt_entry(char *, size_t, unsigned int, const void *);
234 static void p_time(struct shf *, bool, long, int, int,
235 const char *, const char *);
238 c_pwd(const char **wp)
241 bool physical = tobool(Flag(FPHYSICAL));
242 char *p, *allocd = NULL;
244 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
255 wp += builtin_opt.optind;
258 bi_errorf(Ttoo_many_args);
261 p = current_wd[0] ? (physical ? allocd = do_realpath(current_wd) :
263 /* LINTED use of access */
264 if (p && access(p, R_OK) < 0)
266 if (!p && !(p = allocd = ksh_get_wd())) {
267 bi_errorf(Tf_sD_s, "can't determine current directory",
272 afree(allocd, ATEMP);
276 static const char *s_ptr;
277 static int s_get(void);
278 static void s_put(int);
281 c_print(const char **wp)
287 /* print newline; expand backslash sequences */
288 bool po_nl = true, po_exp = true;
289 /* print to history instead of file descriptor / stdout */
290 bool po_hist = false;
291 /* print characters */
292 bool po_char = false;
295 if (wp[0][0] == 'e') {
298 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
301 * MidnightBSD /bin/sh needs a BSD echo, that is,
302 * one that supports -e but does not enable it by
309 #ifndef MKSH_MIDNIGHTBSD01ASH_COMPAT
313 /* Debian Policy 10.4 compliant "echo" builtin */
314 if (*wp && !strcmp(*wp, "-n")) {
315 /* recognise "-n" only as the first arg */
319 /* print everything as-is */
322 bool new_exp = po_exp, new_nl = po_nl;
325 * a compromise between sysV and BSD echo commands:
326 * escape sequences are enabled by default, and -n,
327 * -e and -E are recognised if they appear in argu-
328 * ments with no illegal options (ie, echo -nq will
330 * Different from sysV echo since options are reco-
331 * gnised, different from BSD echo since escape se-
332 * quences are enabled by default.
336 if ((s = *wp) && *s++ == '-' && *s) {
338 switch ((c = *s++)) {
341 goto print_tradparse_ch;
344 goto print_tradparse_ch;
347 goto print_tradparse_ch;
352 goto print_tradparse_arg;
357 /* "print" builtin */
358 const char *opts = "AnpRrsu,";
360 /* print a "--" argument */
361 bool po_pminusminus = false;
363 while ((c = ksh_getopt(wp, &builtin_opt, opts)) != -1)
375 if ((fd = coproc_getfd(W_OK, &emsg)) < 0) {
376 bi_errorf(Tf_coproc, emsg);
381 /* fake BSD echo command */
382 po_pminusminus = true;
393 if (!*(s = builtin_opt.optarg))
395 else if ((fd = check_fd(s, W_OK, &emsg)) < 0) {
396 bi_errorf("-u%s: %s", s, emsg);
404 if (!(builtin_opt.info & GI_MINUSMINUS)) {
405 /* treat a lone "-" like "--" */
406 if (wp[builtin_opt.optind] &&
407 ksh_isdash(wp[builtin_opt.optind]))
408 builtin_opt.optind++;
409 } else if (po_pminusminus)
410 builtin_opt.optind--;
411 wp += builtin_opt.optind;
414 Xinit(xs, xp, 128, ATEMP);
416 if (*wp != NULL && po_char) {
420 if (!evaluate(*wp, &wc, KSH_RETURN_ERROR, true))
424 ts[utf_wctomb(ts, wc)] = 0;
430 Xput(xs, xp, wc & 0xFF);
432 } else if (*wp != NULL) {
435 while ((c = *s++) != '\0') {
437 if (po_exp && c == '\\') {
439 c = unbksl(false, s_get, s_put);
442 /* rejected by generic function */
443 switch ((c = *s++)) {
446 /* AT&T brain damage */
455 } else if ((unsigned int)c > 0xFF) {
456 /* generic function returned Unicode */
457 ts[utf_wctomb(ts, c - 0x100)] = 0;
478 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
481 size_t len = Xlength(xs, xp);
482 bool po_coproc = false;
486 * Ensure we aren't killed by a SIGPIPE while writing to
487 * a coprocess. AT&T ksh doesn't seem to do this (seems
488 * to just check that the co-process is alive which is
491 if (coproc.write >= 0 && coproc.write == fd) {
493 opipe = block_pipe();
500 if ((nwritten = write(fd, s, len)) < 0) {
501 if (errno == EINTR) {
504 /* give the user a chance to ^C out */
506 /* interrupted, try again */
508 opipe = block_pipe();
531 s_put(int c MKSH_A_UNUSED)
537 c_whence(const char **wp)
540 bool pflag = false, vflag = false;
542 while ((optc = ksh_getopt(wp, &builtin_opt, Tpv)) != -1)
553 wp += builtin_opt.optind;
555 return (do_whence(wp, pflag ? FC_PATH :
556 FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, false));
559 /* note: command without -vV is dealt with in comexec() */
561 c_command(const char **wp)
563 int optc, fcflags = FC_BI | FC_FUNC | FC_PATH | FC_WHENCE;
566 while ((optc = ksh_getopt(wp, &builtin_opt, TpVv)) != -1)
569 fcflags |= FC_DEFPATH;
580 wp += builtin_opt.optind;
582 return (do_whence(wp, fcflags, vflag, true));
586 do_whence(const char **wp, int fcflags, bool vflag, bool iscommand)
593 while ((vflag || rv == 0) && (id = *wp++) != NULL) {
597 if (fcflags & FC_WHENCE)
598 tp = ktsearch(&keywords, id, h);
599 if (!tp && (fcflags & FC_WHENCE)) {
600 tp = ktsearch(&aliases, id, h);
601 if (tp && !(tp->flag & ISSET))
605 tp = findcom(id, fcflags);
611 shf_puts(id, shl_stdout);
618 shprintf(" is a %sshell %s",
619 (tp->flag & SPEC_BI) ? "special " : "",
624 shf_puts(" is a", shl_stdout);
625 if (tp->flag & EXPORT)
626 shf_puts("n exported", shl_stdout);
627 if (tp->flag & TRACE)
628 shf_puts(" traced", shl_stdout);
629 if (!(tp->flag & ISSET)) {
630 shf_puts(" undefined", shl_stdout);
632 shprintf(" (autoload from %s)",
635 shf_puts(T_function, shl_stdout);
640 if (tp->flag & ISSET) {
642 shprintf("%s is ", id);
643 if (tp->type == CTALIAS)
644 shprintf("a tracked %s%s for ",
645 (tp->flag & EXPORT) ?
649 shf_puts(tp->val.s, shl_stdout);
652 shprintf(Tnot_found_s, id);
658 shprintf("%s is an %s%s for ", id,
659 (tp->flag & EXPORT) ? "exported " : "",
661 } else if (iscommand)
662 shprintf("%s %s=", Talias, id);
663 print_value_quoted(shl_stdout, tp->val.s);
667 shf_puts(" is a reserved word", shl_stdout);
671 bi_errorf("%s is of unknown type %d", id, tp->type);
676 shf_putc('\n', shl_stdout);
681 /* typeset, global, export, and readonly */
682 static void c_typeset_vardump(struct tbl *, uint32_t, int, bool, bool);
683 static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
686 c_typeset(const char **wp)
689 uint32_t fset = 0, fclr = 0, flag;
690 int thing = 0, field = 0, base = 0, i;
693 const char *fieldstr = NULL, *basestr = NULL;
694 bool localv = false, func = false, pflag = false, istset = true;
695 enum namerefflag new_refflag = SRF_NOP;
713 /* called with 'typeset -' */
722 /* see comment below regarding possible opions */
723 opts = istset ? "L#R#UZ#afi#lnprtux" : "p";
725 builtin_opt.flags |= GF_PLUSOPT;
727 * AT&T ksh seems to have 0-9 as options which are multiplied
728 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
729 * sets right justify in a field of 12). This allows options
730 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
731 * does not allow the number to be specified as a separate argument
732 * Here, the number must follow the RLZi option, but is optional
733 * (see the # kludge in ksh_getopt()).
735 while ((i = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
740 fieldstr = builtin_opt.optarg;
744 fieldstr = builtin_opt.optarg;
748 * AT&T ksh uses u, but this conflicts with
749 * upper/lower case. If this option is changed,
750 * need to change the -U below as well
756 fieldstr = builtin_opt.optarg;
760 * this is supposed to set (-a) or unset (+a) the
761 * indexed array attribute; it does nothing on an
762 * existing regular string or indexed array though
770 basestr = builtin_opt.optarg;
776 new_refflag = (builtin_opt.info & GI_PLUS) ?
777 SRF_DISABLE : SRF_ENABLE;
779 /* export, readonly: POSIX -p flag */
781 /* typeset: show values as well */
793 /* upper case / autoload */
802 if (builtin_opt.info & GI_PLUS) {
813 if (fieldstr && !bi_getn(fieldstr, &field))
816 if (!getn(basestr, &base)) {
817 bi_errorf(Tf_sD_s, "bad integer base", basestr);
820 if (base < 1 || base > 36)
824 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
825 (wp[builtin_opt.optind][0] == '-' ||
826 wp[builtin_opt.optind][0] == '+') &&
827 wp[builtin_opt.optind][1] == '\0') {
828 thing = wp[builtin_opt.optind][0];
829 builtin_opt.optind++;
832 if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
833 new_refflag != SRF_NOP)) {
834 bi_errorf("only -t, -u and -x options may be used with -f");
837 if (wp[builtin_opt.optind]) {
839 * Take care of exclusions.
840 * At this point, flags in fset are cleared in fclr and vice
841 * versa. This property should be preserved.
844 /* LCASEV has priority over UCASEV_AL */
847 /* LJUST has priority over RJUST */
849 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
855 * Setting these attributes clears the others, unless they
856 * are also set in this command
858 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
859 INTEGER | INT_U | INT_L)) || new_refflag != SRF_NOP)
860 fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
861 LCASEV | INTEGER | INT_U | INT_L);
863 if (new_refflag != SRF_NOP) {
864 fclr &= ~(ARRAY | ASSOC);
865 fset &= ~(ARRAY | ASSOC);
868 if (new_refflag == SRF_DISABLE)
872 /* set variables and attributes */
873 if (wp[builtin_opt.optind] &&
874 /* not "typeset -p varname" */
875 !(!func && pflag && !(fset | fclr))) {
881 for (i = builtin_opt.optind; wp[i]; i++) {
883 f = findfunc(wp[i], hash(wp[i]),
884 tobool(fset & UCASEV_AL));
886 /* AT&T ksh does ++rv: bogus */
894 fpFUNCTf(shl_stdout, 0,
895 tobool(f->flag & FKSH),
897 shf_putc('\n', shl_stdout);
899 } else if (!typeset(wp[i], fset, fclr, field, base)) {
900 bi_errorf(Tf_sD_s, wp[i], Tnot_ident);
907 /* list variables and attributes */
909 /* no difference at this point.. */
912 for (l = e->loc; l; l = l->next) {
913 for (p = ktsort(&l->funs); (vp = *p++); ) {
914 if (flag && (vp->flag & flag) == 0)
917 fpFUNCTf(shl_stdout, 0,
918 tobool(vp->flag & FKSH),
919 vp->name, vp->val.t);
921 shf_puts(vp->name, shl_stdout);
922 shf_putc('\n', shl_stdout);
925 } else if (wp[builtin_opt.optind]) {
926 for (i = builtin_opt.optind; wp[i]; i++) {
927 varsearch(e->loc, &vp, wp[i], hash(wp[i]));
928 c_typeset_vardump(vp, flag, thing, pflag, istset);
931 c_typeset_vardump_recursive(e->loc, flag, thing, pflag, istset);
936 c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
937 bool pflag, bool istset)
939 struct tbl **blockvars, *vp;
942 c_typeset_vardump_recursive(l->next, flag, thing, pflag, istset);
943 blockvars = ktsort(&l->vars);
944 while ((vp = *blockvars++))
945 c_typeset_vardump(vp, flag, thing, pflag, istset);
946 /*XXX doesn’t this leak? */
950 c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, bool pflag,
961 * See if the parameter is set (for arrays, if any
964 for (tvp = vp; tvp; tvp = tvp->u.array)
965 if (tvp->flag & ISSET) {
971 * Check attributes - note that all array elements
972 * have (should have?) the same attributes, so checking
973 * the first is sufficient.
975 * Report an unset param only if the user has
976 * explicitly given it some attribute (like export);
977 * otherwise, after "echo $FOO", we would report FOO...
979 if (!any_set && !(vp->flag & USERATTRIB))
981 if (flag && (vp->flag & flag) == 0)
983 if (!(vp->flag & ARRAY))
984 /* optimise later conditionals */
988 * Ignore array elements that aren't set unless there
989 * are no set elements, in which case the first is
992 if (any_set && !(vp->flag & ISSET))
995 if (!thing && !flag) {
997 shprintf(Tf_s_s_sN, Tset, "-A", vp->name);
1001 * AT&T ksh prints things like export, integer,
1002 * leftadj, zerofill, etc., but POSIX says must
1003 * be suitable for re-entry...
1005 shprintf(Tf_s_s, Ttypeset, "");
1006 if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
1007 shprintf(Tf__c_, 'n');
1008 if ((vp->flag & INTEGER))
1009 shprintf(Tf__c_, 'i');
1010 if ((vp->flag & EXPORT))
1011 shprintf(Tf__c_, 'x');
1012 if ((vp->flag & RDONLY))
1013 shprintf(Tf__c_, 'r');
1014 if ((vp->flag & TRACE))
1015 shprintf(Tf__c_, 't');
1016 if ((vp->flag & LJUST))
1017 shprintf("-L%d ", vp->u2.field);
1018 if ((vp->flag & RJUST))
1019 shprintf("-R%d ", vp->u2.field);
1020 if ((vp->flag & ZEROFIL))
1021 shprintf(Tf__c_, 'Z');
1022 if ((vp->flag & LCASEV))
1023 shprintf(Tf__c_, 'l');
1024 if ((vp->flag & UCASEV_AL))
1025 shprintf(Tf__c_, 'u');
1026 if ((vp->flag & INT_U))
1027 shprintf(Tf__c_, 'U');
1029 shprintf(Tf_s_s, istset ? Ttypeset :
1030 (flag & EXPORT) ? Texport : Treadonly, "");
1033 shprintf("%s[%lu]", vp->name, arrayindex(vp));
1035 shf_puts(vp->name, shl_stdout);
1036 if ((!thing && !flag && pflag) ||
1037 (thing == '-' && (vp->flag & ISSET))) {
1039 shf_putc('=', shl_stdout);
1040 /* AT&T ksh can't have justified integers... */
1041 if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
1042 shf_puts(s, shl_stdout);
1044 print_value_quoted(shl_stdout, s);
1046 shf_putc('\n', shl_stdout);
1049 * Only report first 'element' of an array with
1054 } while ((vp = vp->u.array));
1058 c_alias(const char **wp)
1060 struct table *t = &aliases;
1061 int rv = 0, prefix = 0;
1062 bool rflag = false, tflag, Uflag = false, pflag = false;
1066 builtin_opt.flags |= GF_PLUSOPT;
1067 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
1068 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
1072 t = NULL; /* fix "alias -dt" */
1088 * kludge for tracked alias initialization
1089 * (don't do a path search, just make an entry)
1104 wp += builtin_opt.optind;
1106 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
1107 (wp[0][0] == '-' || wp[0][0] == '+') && wp[0][1] == '\0') {
1112 tflag = t == &taliases;
1114 /* "hash -r" means reset all the tracked aliases.. */
1116 static const char *args[] = {
1117 Tunalias, "-ta", NULL
1120 if (!tflag || *wp) {
1121 shprintf("%s: -r flag can only be used with -t"
1122 " and without arguments\n", Talias);
1125 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1126 return (c_unalias(args));
1130 struct tbl *ap, **p;
1132 for (p = ktsort(t); (ap = *p++) != NULL; )
1133 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
1135 shprintf(Tf_s_, Talias);
1136 shf_puts(ap->name, shl_stdout);
1137 if (prefix != '+') {
1138 shf_putc('=', shl_stdout);
1139 print_value_quoted(shl_stdout, ap->val.s);
1141 shf_putc('\n', shl_stdout);
1145 for (; *wp != NULL; wp++) {
1146 const char *alias = *wp, *val, *newval;
1147 char *xalias = NULL;
1151 if ((val = cstrchr(alias, '='))) {
1152 strndupx(xalias, alias, val++ - alias, ATEMP);
1156 if (val == NULL && !tflag && !xflag) {
1157 ap = ktsearch(t, alias, h);
1158 if (ap != NULL && (ap->flag&ISSET)) {
1160 shprintf(Tf_s_, Talias);
1161 shf_puts(ap->name, shl_stdout);
1162 if (prefix != '+') {
1163 shf_putc('=', shl_stdout);
1164 print_value_quoted(shl_stdout, ap->val.s);
1166 shf_putc('\n', shl_stdout);
1168 shprintf(Tf_s_s_sN, alias, Talias, Tnot_found);
1173 ap = ktenter(t, alias, h);
1174 ap->type = tflag ? CTALIAS : CALIAS;
1175 /* Are we setting the value or just some flags? */
1176 if ((val && !tflag) || (!val && tflag && !Uflag)) {
1177 if (ap->flag&ALLOC) {
1178 ap->flag &= ~(ALLOC|ISSET);
1179 afree(ap->val.s, APERM);
1181 /* ignore values for -t (AT&T ksh does this) */
1183 search_path(alias, path, X_OK, NULL) :
1186 strdupx(ap->val.s, newval, APERM);
1187 ap->flag |= ALLOC|ISSET;
1191 ap->flag |= DEFINED;
1196 afree(xalias, ATEMP);
1203 c_unalias(const char **wp)
1205 struct table *t = &aliases;
1210 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
1217 /* fix "unalias -dt" */
1233 wp += builtin_opt.optind;
1235 for (; *wp != NULL; wp++) {
1236 ap = ktsearch(t, *wp, hash(*wp));
1242 if (ap->flag&ALLOC) {
1243 ap->flag &= ~(ALLOC|ISSET);
1244 afree(ap->val.s, APERM);
1246 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1252 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
1253 if (ap->flag&ALLOC) {
1254 ap->flag &= ~(ALLOC|ISSET);
1255 afree(ap->val.s, APERM);
1257 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1265 c_let(const char **wp)
1271 /* AT&T ksh does this */
1272 bi_errorf(Tno_args);
1274 for (wp++; *wp; wp++)
1275 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
1276 /* distinguish error from zero result */
1285 c_jobs(const char **wp)
1287 int optc, flag = 0, nflag = 0, rv = 0;
1289 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1301 /* debugging: print zombies */
1307 wp += builtin_opt.optind;
1309 if (j_jobs(NULL, flag, nflag))
1313 if (j_jobs(*wp, flag, nflag))
1319 #ifndef MKSH_UNEMPLOYED
1321 c_fgbg(const char **wp)
1323 bool bg = strcmp(*wp, Tbg) == 0;
1326 if (!Flag(FMONITOR)) {
1327 bi_errorf("job control not enabled");
1330 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1332 wp += builtin_opt.optind;
1335 rv = j_resume(*wp, bg);
1337 rv = j_resume("%%", bg);
1338 /* fg returns $? of the job unless POSIX */
1339 return ((bg | Flag(FPOSIX)) ? 0 : rv);
1343 /* format a single kill item */
1345 kill_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1347 const struct kill_info *ki = (const struct kill_info *)arg;
1350 shf_snprintf(buf, buflen, "%*u %*s %s",
1352 ki->name_width, sigtraps[i].name,
1357 c_kill(const char **wp)
1364 /* assume old style options if -digits or -UPPERCASE */
1365 if ((p = wp[1]) && *p == '-' && (ksh_isdigit(p[1]) ||
1366 ksh_isupper(p[1]))) {
1367 if (!(t = gettrap(p + 1, false, false))) {
1368 bi_errorf(Tbad_sig_s, p + 1);
1371 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1375 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1381 if (!(t = gettrap(builtin_opt.optarg,
1383 bi_errorf(Tbad_sig_s,
1384 builtin_opt.optarg);
1391 i = builtin_opt.optind;
1393 if ((lflag && t) || (!wp[i] && !lflag)) {
1395 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1396 " { job | pid | pgrp } ...\n"
1397 "\tkill -l [exit_status ...]\n", shl_out);
1405 for (; wp[i]; i++) {
1406 if (!bi_getn(wp[i], &n))
1408 #if (ksh_NSIG <= 128)
1409 if (n > 128 && n < 128 + ksh_NSIG)
1412 if (n > 0 && n < ksh_NSIG)
1413 shprintf(Tf_sN, sigtraps[n].name);
1417 } else if (Flag(FPOSIX)) {
1419 while (n < ksh_NSIG) {
1420 shf_puts(sigtraps[n].name, shl_stdout);
1421 shf_putc(++n == ksh_NSIG ? '\n' : ' ',
1425 ssize_t w, mess_cols = 0, mess_octs = 0;
1426 int j = ksh_NSIG - 1;
1427 struct kill_info ki = { 0, 0 };
1431 } while ((j /= 10));
1433 for (j = 1; j < ksh_NSIG; j++) {
1434 w = strlen(sigtraps[j].name);
1435 if (w > ki.name_width)
1437 w = strlen(sigtraps[j].mess);
1440 w = utf_mbswidth(sigtraps[j].mess);
1445 print_columns(shl_stdout, (unsigned int)(ksh_NSIG - 1),
1446 kill_fmt_entry, (void *)&ki,
1447 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1448 ki.num_width + 1 + ki.name_width + 1 + mess_cols,
1454 sig = t ? t->signal : SIGTERM;
1455 for (; (p = wp[i]); i++) {
1459 } else if (!getn(p, &n)) {
1460 bi_errorf(Tf_sD_s, p,
1461 "arguments must be jobs or process IDs");
1464 if (mksh_kill(n, sig) < 0) {
1465 bi_errorf(Tf_sD_s, p, cstrerror(errno));
1474 getopts_reset(int val)
1477 ksh_getopt_reset(&user_opt, GF_NONAME |
1478 (Flag(FPOSIX) ? 0 : GF_PLUSOPT));
1479 user_opt.optind = user_opt.uoptind = val;
1484 c_getopts(const char **wp)
1487 const char *opts, *var;
1489 struct tbl *vq, *voptarg;
1491 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1493 wp += builtin_opt.optind;
1497 bi_errorf(Tf_sD_s, "options", Tno_args);
1503 bi_errorf(Tf_sD_s, Tname, Tno_args);
1506 if (!*var || *skip_varname(var, true)) {
1507 bi_errorf(Tf_sD_s, var, Tnot_ident);
1511 if (e->loc->next == NULL) {
1512 internal_warningf(Tf_sD_s, Tgetopts, Tno_args);
1515 /* Which arguments are we parsing... */
1517 wp = e->loc->next->argv;
1519 *--wp = e->loc->next->argv[0];
1521 /* Check that our saved state won't cause a core dump... */
1522 for (argc = 0; wp[argc]; argc++)
1524 if (user_opt.optind > argc ||
1526 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1527 bi_errorf("arguments changed since last call");
1531 user_opt.optarg = NULL;
1532 optc = ksh_getopt(wp, &user_opt, opts);
1534 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1540 * POSIX says var is set to ? at end-of-options, AT&T ksh
1541 * sets it to null - we go with POSIX...
1543 buf[0] = optc < 0 ? '?' : optc;
1547 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1548 user_opt.uoptind = user_opt.optind;
1550 voptarg = global("OPTARG");
1551 /* AT&T ksh clears ro and int */
1552 voptarg->flag &= ~RDONLY;
1553 /* Paranoia: ensure no bizarre results. */
1554 if (voptarg->flag & INTEGER)
1555 typeset("OPTARG", 0, INTEGER, 0, 0);
1556 if (user_opt.optarg == NULL)
1559 /* This can't fail (have cleared readonly/integer) */
1560 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1565 /* Error message already printed (integer, readonly) */
1566 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1569 typeset(var, EXPORT, 0, 0, 0);
1571 return (optc < 0 ? 1 : rv);
1574 #ifndef MKSH_NO_CMDLINE_EDITING
1576 c_bind(const char **wp)
1586 while ((optc = ksh_getopt(wp, &builtin_opt,
1605 wp += builtin_opt.optind;
1609 rv = x_bind(NULL, NULL,
1615 for (; *wp != NULL; wp++) {
1616 if ((cp = cstrchr(*wp, '=')) == NULL)
1619 strdupx(up, *wp, ATEMP);
1620 up[cp++ - *wp] = '\0';
1622 if (x_bind(up ? up : *wp, cp,
1636 c_shift(const char **wp)
1638 struct block *l = e->loc;
1643 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1645 arg = wp[builtin_opt.optind];
1649 else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
1650 /* error already printed */
1653 } else if (!(n = val)) {
1657 bi_errorf(Tf_sD_s, arg, "bad number");
1661 bi_errorf("nothing to shift");
1664 l->argv[n] = l->argv[0];
1671 c_umask(const char **wp)
1675 bool symbolic = false;
1678 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1686 cp = wp[builtin_opt.optind];
1688 old_umask = umask((mode_t)0);
1694 old_umask = ~old_umask;
1696 for (i = 0; i < 3; i++) {
1699 for (j = 0; j < 3; j++)
1700 if (old_umask & (1 << (8 - (3*i + j))))
1705 shprintf(Tf_sN, buf);
1707 shprintf("%#3.3o\n", (unsigned int)old_umask);
1711 if (ksh_isdigit(*cp)) {
1713 while (*cp >= ord('0') && *cp <= ord('7')) {
1714 new_umask = new_umask * 8 + ksh_numdig(*cp);
1718 bi_errorf("bad number");
1722 /* symbolic format */
1723 int positions, new_val;
1726 old_umask = umask((mode_t)0);
1727 /* in case of error */
1729 old_umask = ~old_umask;
1730 new_umask = old_umask;
1733 while (*cp && vstrchr(Taugo, *cp))
1751 if (!vstrchr("=+-", op = *cp))
1755 while (*cp && vstrchr("rwxugoXs", *cp))
1757 case 'r': new_val |= 04; break;
1758 case 'w': new_val |= 02; break;
1759 case 'x': new_val |= 01; break;
1761 new_val |= old_umask >> 6;
1764 new_val |= old_umask >> 3;
1767 new_val |= old_umask >> 0;
1770 if (old_umask & 0111)
1777 new_val = (new_val & 07) * positions;
1780 new_umask &= ~new_val;
1783 new_umask = new_val |
1784 (new_umask & ~(positions * 07));
1787 new_umask |= new_val;
1792 } else if (!vstrchr("=+-", *cp))
1796 bi_errorf("bad mask");
1799 new_umask = ~new_umask;
1807 c_dot(const char **wp)
1809 const char *file, *cp, **argv;
1810 int argc, rv, errcode;
1812 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1815 if ((cp = wp[builtin_opt.optind]) == NULL) {
1816 bi_errorf(Tno_args);
1819 file = search_path(cp, path, R_OK, &errcode);
1820 if (!file && errcode == ENOENT && wp[0][0] == 's' &&
1821 search_access(cp, R_OK) == 0)
1824 bi_errorf(Tf_sD_s, cp, cstrerror(errcode));
1828 /* Set positional parameters? */
1829 if (wp[builtin_opt.optind + 1]) {
1830 argv = wp + builtin_opt.optind;
1832 argv[0] = e->loc->argv[0];
1833 for (argc = 0; argv[argc + 1]; argc++)
1839 /* SUSv4: OR with a high value never written otherwise */
1841 if ((rv = include(file, argc, argv, false)) < 0) {
1842 /* should not happen */
1843 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
1846 if (exstat & 0x4000)
1847 /* detect old exstat, use 0 in that case */
1853 c_wait(const char **wp)
1857 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1859 wp += builtin_opt.optind;
1861 while (waitfor(NULL, &sig) >= 0)
1866 rv = waitfor(*wp, &sig);
1868 /* magic exit code: bad job-id */
1869 rv = sig ? sig : 127;
1874 static char REPLY[] = "REPLY";
1876 c_read(const char **wp)
1878 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1879 int c, fd = 0, rv = 0;
1880 bool savehist = false, intoarray = false, aschars = false;
1881 bool rawmode = false, expanding = false;
1882 bool lastparmmode = false, lastparmused = false;
1883 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1885 size_t bytesleft = 128, bytesread;
1886 struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
1887 char *cp, *allocd = NULL, *xp;
1892 bool restore_tios = false;
1893 /* to catch read -aN2 foo[i] */
1894 bool subarray = false;
1896 bool hastimeout = false;
1897 struct timeval tv, tvlim;
1898 #define c_read_opts "Aad:N:n:prst:u,"
1900 #define c_read_opts "Aad:N:n:prsu,"
1903 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1912 delim = builtin_opt.optarg[0];
1916 readmode = c == 'N' ? BYTES : UPTO;
1917 if (!bi_getn(builtin_opt.optarg, &c))
1920 readmode = readmode == BYTES ? READALL : UPTO;
1923 bytesleft = (unsigned int)c;
1926 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1927 bi_errorf(Tf_coproc, ccp);
1939 if (parse_usec(builtin_opt.optarg, &tv)) {
1940 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno),
1941 builtin_opt.optarg);
1948 if (!builtin_opt.optarg[0])
1950 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1951 bi_errorf(Tf_sD_sD_s, "-u", builtin_opt.optarg, ccp);
1958 wp += builtin_opt.optind;
1962 if (intoarray && wp[1] != NULL) {
1963 bi_errorf(Ttoo_many_args);
1967 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1968 strdupx(allocd, *wp, ATEMP);
1969 allocd[ccp - *wp] = '\0';
1973 * AT&T ksh says it prints prompt on fd if it's open
1974 * for writing and is a tty, but it doesn't do it
1975 * (it also doesn't check the interactive flag,
1976 * as is indicated in the Korn Shell book).
1978 shf_puts(ccp + 1, shl_out);
1983 Xinit(xs, xp, bytesleft, ATEMP);
1985 if (readmode == LINES)
1987 else if (isatty(fd)) {
1988 x_mkraw(fd, &tios, true);
1989 restore_tios = true;
1995 timeradd(&tvlim, &tv, &tvlim);
2005 FD_SET((unsigned int)fd, &fdset);
2007 timersub(&tvlim, &tv, &tv);
2008 if (tv.tv_sec < 0) {
2009 /* timeout expired globally */
2014 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
2018 /* timeout expired for this call */
2020 /* fake EOF read; all cases return 1 */
2021 goto c_read_didread;
2023 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
2030 if ((bytesread = blocking_read(fd, xp, bytesleft)) == (size_t)-1) {
2031 if (errno == EINTR) {
2032 /* check whether the signal would normally kill */
2033 if (!fatal_trap_check()) {
2034 /* no, just ignore the signal */
2035 goto c_read_readloop;
2037 /* pretend the read was killed */
2039 /* unexpected error */
2040 bi_errorf(Tf_s, cstrerror(errno));
2049 if (bytesread == 0) {
2050 /* end of file reached */
2052 goto c_read_readdone;
2055 XcheckN(xs, xp, bytesleft);
2060 /* end of file reached */
2063 goto c_read_readdone;
2066 if (bytesread == 0) {
2067 /* end of file reached */
2069 /* may be partial read: $? = 1, but content */
2070 goto c_read_readdone;
2073 if ((bytesleft -= bytesread) == 0)
2074 goto c_read_readdone;
2077 if (bytesread == 0) {
2078 /* end of file reached */
2080 goto c_read_readdone;
2082 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
2083 /* skip any read NULs unless delimiter */
2089 if (Flag(FTALKING_I) && isatty(fd)) {
2091 * set prompt in case this is
2092 * called from .profile or $ENV
2094 set_prompt(PS2, NULL);
2097 /* drop the backslash */
2099 /* and the delimiter */
2102 } else if (c == delim) {
2103 goto c_read_readdone;
2104 } else if (!rawmode && c == '\\') {
2111 goto c_read_readloop;
2114 bytesread = Xlength(xs, xp);
2118 * state: we finished reading the input and NUL terminated it
2119 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
2120 * rv = 1 if EOF, 0 otherwise (errors handled already)
2124 /* clean up coprocess if needed, on EOF */
2125 coproc_read_close(fd);
2126 if (readmode == READALL)
2127 /* EOF is no error here */
2132 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
2134 ccp = cp = Xclose(xs, xp);
2136 XinitN(xs, 128, ATEMP);
2139 subarray = last_lookup_was_array;
2140 if (vp->flag & RDONLY) {
2142 bi_errorf(Tf_ro, *wp);
2148 /* counter for array index */
2149 c = subarray ? arrayindex(vp) : 0;
2150 /* exporting an array is currently pointless */
2151 unset(vp, subarray ? 0 : 1);
2154 /* skip initial IFS whitespace */
2155 while (bytesread && is_ifsws(*ccp)) {
2159 /* trim trailing IFS whitespace */
2160 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
2165 xp = Xstring(xs, xp);
2166 /* generate next word */
2170 goto c_read_splitdone;
2171 /* zero out next parameters */
2172 goto c_read_gotword;
2177 bytesleft = utf_ptradj(ccp);
2178 while (bytesleft && bytesread) {
2183 if (xp[-1] == '\0') {
2187 goto c_read_gotword;
2190 if (!intoarray && wp[1] == NULL)
2191 lastparmmode = true;
2194 /* copy until IFS character */
2201 goto c_read_splitcopy;
2202 } else if (ctype(ch, C_IFS)) {
2204 } else if (!rawmode && ch == '\\') {
2214 xsave = Xsavepos(xs, xp);
2215 /* copy word delimiter: IFSWS+IFS,IFSWS */
2221 if (!ctype(ch, C_IFS))
2223 if (lastparmmode && !expanding && !rawmode && ch == '\\') {
2233 if (!ctype(ch, C_IFSWS))
2236 while (bytesread && is_ifsws(*ccp)) {
2242 /* if no more parameters, rinse and repeat */
2243 if (lastparmmode && bytesread) {
2244 lastparmused = true;
2245 goto c_read_splitlast;
2247 /* get rid of the delimiter unless we pack the rest */
2249 xp = Xrestpos(xs, xp, xsave);
2254 /* array element passed, accept first read */
2256 bi_errorf("nested arrays not yet supported");
2257 goto c_read_spliterr;
2264 vq = arraysearch(vp, c++);
2267 /* must be checked before exporting */
2268 if (vq->flag & RDONLY)
2269 goto c_read_splitro;
2271 typeset(*wp, EXPORT, 0, 0, 0);
2273 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
2274 goto c_read_spliterr;
2276 setint_v(vq, vq, false);
2277 /* protect from UTFMODE changes */
2280 if (intoarray || *++wp != NULL)
2281 goto c_read_splitloop;
2288 afree(allocd, ATEMP);
2291 mksh_tcset(fd, &tios);
2297 c_eval(const char **wp)
2299 struct source *s, *saves = source;
2300 unsigned char savef;
2303 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2305 s = pushs(SWORDS, ATEMP);
2306 s->u.strv = wp + builtin_opt.optind;
2309 * The following code handles the case where the command is
2310 * empty due to failed command substitution, for example by
2312 * This has historically returned 1 by AT&T ksh88. In this
2313 * case, shell() will not set or change exstat because the
2314 * compiled tree is empty, so it will use the value we pass
2315 * from subst_exstat, which is cleared in execute(), so it
2316 * should have been 0 if there were no substitutions.
2318 * POSIX however says we don't do this, even though it is
2319 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2320 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2322 * 2.9.1: Simple Commands
2323 * ... If there is a command name, execution shall
2324 * continue as described in 2.9.1.1 [Command Search
2325 * and Execution]. If there is no command name, but
2326 * the command contained a command substitution, the
2327 * command shall complete with the exit status of the
2328 * last command substitution performed.
2329 * 2.9.1.1: Command Search and Execution
2330 * (1) a. If the command name matches the name of a
2331 * special built-in utility, that special built-in
2332 * utility shall be invoked.
2334 * If there are no arguments, or only null arguments,
2335 * eval shall return a zero exit status; ...
2337 /* AT&T ksh88: use subst_exstat */
2338 /* exstat = subst_exstat; */
2339 /* SUSv4: OR with a high value never written otherwise */
2342 savef = Flag(FERREXIT);
2343 Flag(FERREXIT) |= 0x80;
2344 rv = shell(s, false);
2345 Flag(FERREXIT) = savef;
2348 if (exstat & 0x4000)
2349 /* detect old exstat, use 0 in that case */
2355 c_trap(const char **wp)
2361 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2363 wp += builtin_opt.optind;
2368 shf_puts("trap -- ", shl_stdout);
2369 print_value_quoted(shl_stdout, p->trap);
2370 shprintf(Tf__sN, p->name);
2377 if (getn(*wp, &i)) {
2378 /* first argument is a signal number, reset them all */
2381 /* first argument must be a command, then */
2388 /* set/clear the traps */
2391 if (!(p = gettrap(*wp++, true, true))) {
2392 warningf(true, Tbad_sig_ss, builtin_argv0, wp[-1]);
2400 c_exitreturn(const char **wp)
2406 goto c_exitreturn_err;
2407 exstat = bi_getn(wp[1], &n) ? (n & 0xFF) : 1;
2408 } else if (trap_exstat != -1)
2409 exstat = trap_exstat;
2411 if (wp[0][0] == 'r') {
2416 * need to tell if this is exit or return so trap exit will
2417 * work right (POSIX)
2419 for (ep = e; ep; ep = ep->oenv)
2420 if (STOP_RETURN(ep->type)) {
2426 if (how == LEXIT && !really_exit && j_stopped_running()) {
2431 /* get rid of any I/O redirections */
2437 bi_errorf(Ttoo_many_args);
2442 c_brkcont(const char **wp)
2446 struct env *ep, *last_ep = NULL;
2449 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2451 arg = wp[builtin_opt.optind];
2455 else if (!bi_getn(arg, &n))
2458 /* AT&T ksh does this for non-interactive shells only - weird */
2459 bi_errorf("%s: bad value", arg);
2462 quit = (unsigned int)n;
2464 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2465 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2466 if (ep->type == E_LOOP) {
2469 ep->flags |= EF_BRKCONT_PASS;
2475 * AT&T ksh doesn't print a message - just does what it
2476 * can. We print a message 'cause it helps in debugging
2477 * scripts, but don't generate an error (ie, keep going).
2479 if ((unsigned int)n == quit) {
2480 warningf(true, "%s: can't %s", wp[0], wp[0]);
2484 * POSIX says if n is too big, the last enclosing loop
2485 * shall be used. Doesn't say to print an error but we
2486 * do anyway 'cause the user messed up.
2489 last_ep->flags &= ~EF_BRKCONT_PASS;
2490 warningf(true, "%s: can only %s %u level(s)",
2491 wp[0], wp[0], (unsigned int)n - quit);
2494 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2502 c_set(const char **wp)
2506 struct block *l = e->loc;
2509 if (wp[1] == NULL) {
2510 static const char *args[] = { Tset, "-", NULL };
2511 return (c_typeset(args));
2514 if ((argi = parse_args(wp, OF_SET, &setargs)) < 0)
2522 while (*++wp != NULL)
2523 strdupx(*wp, *wp, &l->area);
2524 l->argc = wp - owp - 1;
2525 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2526 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2530 * POSIX says set exit status is 0, but old scripts that use
2531 * getopt(1) use the construct
2532 * set -- $(getopt ab:c "$@")
2533 * which assumes the exit value set will be that of the $()
2534 * (subst_exstat is cleared in execute() so that it will be 0
2535 * if there are no command substitutions).
2537 #ifdef MKSH_LEGACY_MODE
2538 /* traditional behaviour, unless set -o posix */
2539 return (Flag(FPOSIX) ? 0 : subst_exstat);
2541 /* conformant behaviour, unless set -o sh +o posix */
2542 return (Flag(FSH) && !Flag(FPOSIX) ? subst_exstat : 0);
2547 c_unset(const char **wp)
2551 bool unset_var = true;
2553 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2562 /*XXX not reached due to GF_ERROR */
2565 wp += builtin_opt.optind;
2566 for (; (id = *wp) != NULL; wp++)
2568 /* unset variable */
2574 if (n > 3 && id[n-3] == '[' && id[n-2] == '*' &&
2576 strndupx(cp, id, n - 3, ATEMP);
2580 optc = vstrchr(id, '[') ? 0 : 1;
2585 if ((vp->flag&RDONLY)) {
2586 warningf(true, Tf_ro, vp->name);
2591 /* unset function */
2597 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2598 const char *prefix, const char *suffix)
2602 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2603 tv_sec, tv_usec, suffix);
2605 shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
2606 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2610 c_times(const char **wp MKSH_A_UNUSED)
2612 struct rusage usage;
2614 getrusage(RUSAGE_SELF, &usage);
2615 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2616 usage.ru_utime.tv_usec, 0, null, T1space);
2617 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2618 usage.ru_stime.tv_usec, 0, null, "\n");
2620 getrusage(RUSAGE_CHILDREN, &usage);
2621 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2622 usage.ru_utime.tv_usec, 0, null, T1space);
2623 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2624 usage.ru_stime.tv_usec, 0, null, "\n");
2630 * time pipeline (really a statement, not a built-in command)
2633 timex(struct op *t, int f, volatile int *xerrok)
2635 #define TF_NOARGS BIT(0)
2636 #define TF_NOREAL BIT(1) /* don't report real time */
2637 #define TF_POSIX BIT(2) /* report in POSIX format */
2639 struct rusage ru0, ru1, cru0, cru1;
2640 struct timeval usrtime, systime, tv0, tv1;
2643 getrusage(RUSAGE_SELF, &ru0);
2644 getrusage(RUSAGE_CHILDREN, &cru0);
2647 * Two ways of getting cpu usage of a command: just use t0
2648 * and t1 (which will get cpu usage from other jobs that
2649 * finish while we are executing t->left), or get the
2650 * cpu usage of t->left. AT&T ksh does the former, while
2651 * pdksh tries to do the later (the j_usrtime hack doesn't
2652 * really work as it only counts the last job).
2654 timerclear(&j_usrtime);
2655 timerclear(&j_systime);
2656 rv = execute(t->left, f | XTIME, xerrok);
2657 if (t->left->type == TCOM)
2658 tf |= t->left->str[0];
2660 getrusage(RUSAGE_SELF, &ru1);
2661 getrusage(RUSAGE_CHILDREN, &cru1);
2665 if (tf & TF_NOARGS) {
2666 /* ksh93 - report shell times (shell+kids) */
2668 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2669 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2671 timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
2672 timeradd(&usrtime, &j_usrtime, &usrtime);
2673 timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
2674 timeradd(&systime, &j_systime, &systime);
2677 if (!(tf & TF_NOREAL)) {
2678 timersub(&tv1, &tv0, &tv1);
2680 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2681 5, Treal_sp1, "\n");
2683 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2684 5, null, Treal_sp2);
2687 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2688 5, Tuser_sp1, "\n");
2690 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2691 5, null, Tuser_sp2);
2693 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2696 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2697 5, null, " system\n");
2704 timex_hook(struct op *t, char **volatile *app)
2710 ksh_getopt_reset(&opt, 0);
2711 /* start at the start */
2713 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2716 t->str[0] |= TF_POSIX;
2719 errorf(Tf_optfoo, Ttime, Tcolsp,
2720 opt.optarg[0], Tunknown_option);
2722 errorf(Tf_optfoo, Ttime, Tcolsp,
2723 opt.optarg[0], Treq_arg);
2725 /* Copy command words down over options. */
2726 if (opt.optind != 0) {
2727 for (i = 0; i < opt.optind; i++)
2728 afree(wp[i], ATEMP);
2729 for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
2733 t->str[0] |= TF_NOARGS;
2737 /* exec with no args - args case is taken care of in comexec() */
2739 c_exec(const char **wp MKSH_A_UNUSED)
2743 /* make sure redirects stay in place */
2744 if (e->savefd != NULL) {
2745 for (i = 0; i < NUFILE; i++) {
2746 if (e->savefd[i] > 0)
2747 close(e->savefd[i]);
2748 #ifndef MKSH_LEGACY_MODE
2750 * keep all file descriptors > 2 private for ksh,
2751 * but not for POSIX or legacy/kludge sh
2753 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2755 fcntl(i, F_SETFD, FD_CLOEXEC);
2765 c_mknod(const char **wp)
2767 int argc, optc, rv = 0;
2768 bool ismkfifo = false;
2771 mode_t mode = 0, oldmode = 0;
2773 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2776 set = setmode(builtin_opt.optarg);
2778 bi_errorf("invalid file mode");
2781 mode = getmode(set, (mode_t)(DEFFILEMODE));
2782 free_ossetmode(set);
2788 argv = &wp[builtin_opt.optind];
2789 if (argv[0] == NULL)
2791 for (argc = 0; argv[argc]; argc++)
2793 if (argc == 2 && argv[1][0] == 'p')
2795 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2799 oldmode = umask((mode_t)0);
2803 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2804 (argv[1][0] == 'c') ? S_IFCHR : 0;
2807 unsigned long majnum, minnum;
2811 majnum = strtoul(argv[2], &c, 0);
2812 if ((c == argv[2]) || (*c != '\0')) {
2813 bi_errorf(Tf_nonnum, "device", "major", argv[2]);
2816 minnum = strtoul(argv[3], &c, 0);
2817 if ((c == argv[3]) || (*c != '\0')) {
2818 bi_errorf(Tf_nonnum, "device", "minor", argv[3]);
2821 dv = makedev(majnum, minnum);
2822 if ((unsigned long)(major(dv)) != majnum) {
2823 bi_errorf(Tf_toolarge, "device", "major", majnum);
2826 if ((unsigned long)(minor(dv)) != minnum) {
2827 bi_errorf(Tf_toolarge, "device", "minor", minnum);
2830 if (mknod(argv[0], mode, dv))
2831 goto c_mknod_failed;
2832 } else if (mkfifo(argv[0], mode)) {
2834 bi_errorf(Tf_sD_s, argv[0], cstrerror(errno));
2843 bi_errorf("usage: mknod [-m mode] name %s", "b|c major minor");
2844 bi_errorf("usage: mknod [-m mode] name %s", "p");
2850 test(1) roughly accepts the following grammar:
2851 oexpr ::= aexpr | aexpr "-o" oexpr ;
2852 aexpr ::= nexpr | nexpr "-a" aexpr ;
2853 nexpr ::= primary | "!" nexpr ;
2854 primary ::= unary-operator operand
2855 | operand binary-operator operand
2860 unary-operator ::= "-a"|"-r"|"-w"|"-x"|"-e"|"-f"|"-d"|"-c"|"-b"|"-p"|
2861 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|
2862 "-L"|"-h"|"-S"|"-H";
2864 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
2866 "<"|">" # rules used for [[ ... ]] expressions
2868 operand ::= <anything>
2871 /* POSIX says > 1 for errors */
2872 #define T_ERR_EXIT 2
2875 c_test(const char **wp)
2877 int argc, rv, invert = 0;
2881 const char *lhs, **swp;
2885 te.getopnd = ptest_getopnd;
2886 te.eval = test_eval;
2887 te.error = ptest_error;
2889 for (argc = 0; wp[argc]; argc++)
2892 if (strcmp(wp[0], Tbracket) == 0) {
2893 if (strcmp(wp[--argc], "]") != 0) {
2894 bi_errorf("missing ]");
2895 return (T_ERR_EXIT);
2900 te.wp_end = wp + argc;
2903 * Attempt to conform to POSIX special cases. This is pretty
2904 * dumb code straight-forward from the 2008 spec, but unlike
2905 * the old pdksh code doesn't live from so many assumptions.
2906 * It does, though, inline some calls to '(*te.funcname)()'.
2917 if (ptest_isa(&te, TM_NOT)) {
2921 if ((op = ptest_isa(&te, TM_UNOP))) {
2923 rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
2925 if (te.flags & TEF_ERROR)
2926 return (T_ERR_EXIT);
2927 return ((invert & 1) ? rv : !rv);
2929 /* let the parser deal with anything else */
2934 /* use inside knowledge of ptest_getopnd inlined below */
2936 if ((op = ptest_isa(&te, TM_BINOP))) {
2937 /* test lhs op rhs */
2938 rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
2941 if (ptest_isa(&te, tm = TM_AND) || ptest_isa(&te, tm = TM_OR)) {
2943 argc = test_eval(&te, TO_STNZE, lhs, NULL, true);
2944 rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, true);
2951 /* back up to lhs */
2953 if (ptest_isa(&te, TM_NOT)) {
2957 if (ptest_isa(&te, TM_OPAREN)) {
2959 /* skip operand, without evaluation */
2961 /* check for closing parenthesis */
2962 op = ptest_isa(&te, TM_CPAREN);
2963 /* back up to operand */
2965 /* if there was a closing paren, handle it */
2968 /* backing up is done before calling the parser */
2970 /* let the parser deal with it */
2973 if (ptest_isa(&te, TM_NOT)) {
2977 if (ptest_isa(&te, TM_OPAREN)) {
2979 /* skip two operands, without evaluation */
2982 /* check for closing parenthesis */
2983 op = ptest_isa(&te, TM_CPAREN);
2984 /* back up to first operand */
2986 /* if there was a closing paren, handle it */
2989 /* backing up is done before calling the parser */
2991 /* defer this to the parser */
2995 /* "The results are unspecified." */
2997 return (test_parse(&te));
3001 * Generic test routines.
3005 test_isop(Test_meta meta, const char *s)
3008 const struct t_op *tbl;
3010 tbl = meta == TM_UNOP ? u_ops : b_ops;
3013 for (; tbl->op_text[0]; tbl++)
3014 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
3015 return (tbl->op_num);
3021 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
3034 /* Binary operators */
3048 /* consistency check, but does not happen in practice */
3050 te->flags |= TEF_ERROR;
3055 /* for completeness of switch */
3068 return (*opnd1 != '\0');
3072 return (*opnd1 == '\0');
3076 if ((i = *opnd1) == '!' || i == '?')
3078 if ((k = option(opnd1)) == (size_t)-1)
3080 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
3084 /* LINTED use of access */
3085 return (access(opnd1, R_OK) == 0);
3089 /* LINTED use of access */
3090 return (access(opnd1, W_OK) == 0);
3094 return (ksh_access(opnd1, X_OK) == 0);
3100 return (stat(opnd1, &b1) == 0);
3104 return (stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
3108 return (stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
3112 return (stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
3116 return (stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
3120 return (stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
3124 #ifdef MKSH__NO_SYMLINK
3127 return (lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
3132 return (stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
3134 /* -H => HP context dependent files (directories) */
3141 * Append a + to filename and check to see if result is
3142 * a setuid directory. CDF stuff in general is hookey,
3143 * since it breaks for, e.g., the following sequence:
3144 * echo hi >foo+; mkdir foo; echo bye >foo/default;
3145 * chmod u+s foo (foo+ refers to the file with hi in it,
3146 * there is no way to get at the file with bye in it;
3147 * please correct me if I'm wrong about this).
3150 nv = shf_smprintf("%s+", opnd1);
3151 i = (stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
3161 return (stat(opnd1, &b1) == 0 &&
3162 (b1.st_mode & S_ISUID) == S_ISUID);
3166 return (stat(opnd1, &b1) == 0 &&
3167 (b1.st_mode & S_ISGID) == S_ISGID);
3172 return (stat(opnd1, &b1) == 0 &&
3173 (b1.st_mode & S_ISVTX) == S_ISVTX);
3180 return (stat(opnd1, &b1) == 0 && (off_t)b1.st_size > (off_t)0);
3184 if (opnd1 && !bi_getn(opnd1, &i)) {
3185 te->flags |= TEF_ERROR;
3188 i = isatty(opnd1 ? i : 0);
3193 return (stat(opnd1, &b1) == 0 && (uid_t)b1.st_uid == ksheuid);
3197 return (stat(opnd1, &b1) == 0 && (gid_t)b1.st_gid == getegid());
3205 if (te->flags & TEF_DBRACKET) {
3206 if ((i = gmatchx(opnd1, opnd2, false)))
3207 record_match(opnd1);
3210 return (strcmp(opnd1, opnd2) == 0);
3214 if (te->flags & TEF_DBRACKET) {
3215 if ((i = gmatchx(opnd1, opnd2, false)))
3216 record_match(opnd1);
3219 return (strcmp(opnd1, opnd2) != 0);
3223 return (strcmp(opnd1, opnd2) < 0);
3227 return (strcmp(opnd1, opnd2) > 0);
3241 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
3242 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
3243 /* error already printed.. */
3244 te->flags |= TEF_ERROR;
3269 * ksh88/ksh93 succeed if file2 can't be stated
3270 * (subtly different from 'does not exist').
3272 return (stat(opnd1, &b1) == 0 &&
3273 (((s = stat(opnd2, &b2)) == 0 &&
3274 b1.st_mtime > b2.st_mtime) || s < 0));
3279 * ksh88/ksh93 succeed if file1 can't be stated
3280 * (subtly different from 'does not exist').
3282 return (stat(opnd2, &b2) == 0 &&
3283 (((s = stat(opnd1, &b1)) == 0 &&
3284 b1.st_mtime < b2.st_mtime) || s < 0));
3288 return (stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0 &&
3289 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
3291 /* all other cases */
3294 /* throw the error */
3297 (*te->error)(te, 0, "internal error: unknown op");
3302 test_parse(Test_env *te)
3306 rv = test_oexpr(te, 1);
3308 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3309 (*te->error)(te, 0, "unexpected operator/operand");
3311 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3315 test_oexpr(Test_env *te, bool do_eval)
3319 if ((rv = test_aexpr(te, do_eval)))
3321 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3322 return (test_oexpr(te, do_eval) || rv);
3327 test_aexpr(Test_env *te, bool do_eval)
3331 if (!(rv = test_nexpr(te, do_eval)))
3333 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3334 return (test_aexpr(te, do_eval) && rv);
3339 test_nexpr(Test_env *te, bool do_eval)
3341 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3342 return (!test_nexpr(te, do_eval));
3343 return (test_primary(te, do_eval));
3347 test_primary(Test_env *te, bool do_eval)
3349 const char *opnd1, *opnd2;
3353 if (te->flags & TEF_ERROR)
3355 if ((*te->isa)(te, TM_OPAREN)) {
3356 rv = test_oexpr(te, do_eval);
3357 if (te->flags & TEF_ERROR)
3359 if (!(*te->isa)(te, TM_CPAREN)) {
3360 (*te->error)(te, 0, "missing )");
3366 * Binary should have precedence over unary in this case
3367 * so that something like test \( -f = -f \) is accepted
3369 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3370 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3371 if ((op = (*te->isa)(te, TM_UNOP))) {
3372 /* unary expression */
3373 opnd1 = (*te->getopnd)(te, op, do_eval);
3375 (*te->error)(te, -1, Tno_args);
3379 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3382 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3384 (*te->error)(te, 0, "expression expected");
3387 if ((op = (*te->isa)(te, TM_BINOP))) {
3388 /* binary expression */
3389 opnd2 = (*te->getopnd)(te, op, do_eval);
3391 (*te->error)(te, -1, "missing second argument");
3395 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3397 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3401 * Plain test (test and [ .. ]) specific routines.
3405 * Test if the current token is a whatever. Accepts the current token if
3406 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3407 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3410 ptest_isa(Test_env *te, Test_meta meta)
3412 /* Order important - indexed by Test_meta values */
3413 static const char * const tokens[] = {
3414 "-o", "-a", "!", "(", ")"
3418 if (te->pos.wp >= te->wp_end)
3419 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3421 if (meta == TM_UNOP || meta == TM_BINOP)
3422 rv = test_isop(meta, *te->pos.wp);
3423 else if (meta == TM_END)
3426 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3427 TO_NONNULL : TO_NONOP;
3429 /* Accept the token? */
3437 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3439 if (te->pos.wp >= te->wp_end)
3440 return (op == TO_FILTT ? "1" : NULL);
3441 return (*te->pos.wp++);
3445 ptest_error(Test_env *te, int ofs, const char *msg)
3449 te->flags |= TEF_ERROR;
3450 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3451 bi_errorf(Tf_sD_s, op, msg);
3453 bi_errorf(Tf_s, msg);
3456 #ifndef MKSH_NO_LIMITS
3460 /* Magic to divine the 'm' and 'v' limits */
3463 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3464 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3465 #define ULIMIT_V_IS_AS
3466 #elif defined(RLIMIT_VMEM)
3467 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3468 #define ULIMIT_V_IS_AS
3470 #define ULIMIT_V_IS_VMEM
3476 #ifdef ULIMIT_V_IS_VMEM
3477 #define ULIMIT_M_IS_RSS
3478 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3479 #define ULIMIT_M_IS_VMEM
3481 #define ULIMIT_M_IS_RSS
3483 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3484 #undef ULIMIT_M_IS_RSS
3488 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3489 #define ULIMIT_V_IS_VMEM
3492 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3493 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3494 #define ULIMIT_M_IS_VMEM
3497 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3498 (RLIMIT_VMEM == RLIMIT_AS)
3499 #undef ULIMIT_M_IS_VMEM
3502 #if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
3503 # error nonsensical m ulimit
3506 #if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
3507 # error nonsensical v ulimit
3511 /* limit resource */
3513 /* multiply by to get rlim_{cur,max} values */
3514 unsigned int factor;
3521 #define RLIMITS_DEFNS
3522 #define FN(lname,lid,lfac,lopt) \
3523 static const struct { \
3525 unsigned int factor; \
3527 char name[sizeof(lname)]; \
3528 } rlimits_ ## lid = { \
3529 lid, lfac, lopt, lname \
3531 #include "rlimits.gen"
3533 static void print_ulimit(const struct limits *, int);
3534 static int set_ulimit(const struct limits *, const char *, int);
3536 static const struct limits * const rlimits[] = {
3537 #define RLIMITS_ITEMS
3538 #include "rlimits.gen"
3541 static const char rlimits_opts[] =
3542 #define RLIMITS_OPTCS
3543 #include "rlimits.gen"
3547 c_ulimit(const char **wp)
3550 int how = SOFT | HARD, optc, what = 'f';
3553 while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
3565 bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
3571 while (i < NELEM(rlimits)) {
3572 if (rlimits[i]->optchar == what)
3576 internal_warningf("ulimit: %c", what);
3579 if (wp[builtin_opt.optind]) {
3580 if (all || wp[builtin_opt.optind + 1]) {
3581 bi_errorf(Ttoo_many_args);
3584 return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
3587 print_ulimit(rlimits[i], how);
3588 else for (i = 0; i < NELEM(rlimits); ++i) {
3589 shprintf("%-20s ", rlimits[i]->name);
3590 print_ulimit(rlimits[i], how);
3596 set_ulimit(const struct limits *l, const char *v, int how)
3598 rlim_t val = (rlim_t)0;
3599 struct rlimit limit;
3601 if (strcmp(v, "unlimited") == 0)
3602 val = (rlim_t)RLIM_INFINITY;
3606 if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
3609 * Avoid problems caused by typos that evaluate misses due
3610 * to evaluating unset parameters to 0...
3611 * If this causes problems, will have to add parameter to
3612 * evaluate() to control if unset params are 0 or an error.
3614 if (!rval && !ksh_isdigit(v[0])) {
3615 bi_errorf("invalid %s limit: %s", l->name, v);
3618 val = (rlim_t)((rlim_t)rval * l->factor);
3621 if (getrlimit(l->resource, &limit) < 0) {
3623 bi_errorf("limit %s could not be read, contact the mksh developers: %s",
3624 l->name, cstrerror(errno));
3626 /* some can't be read */
3627 limit.rlim_cur = RLIM_INFINITY;
3628 limit.rlim_max = RLIM_INFINITY;
3631 limit.rlim_cur = val;
3633 limit.rlim_max = val;
3634 if (!setrlimit(l->resource, &limit))
3637 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3639 bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
3644 print_ulimit(const struct limits *l, int how)
3646 rlim_t val = (rlim_t)0;
3647 struct rlimit limit;
3649 if (getrlimit(l->resource, &limit)) {
3650 shf_puts("unknown\n", shl_stdout);
3654 val = limit.rlim_cur;
3655 else if (how & HARD)
3656 val = limit.rlim_max;
3657 if (val == (rlim_t)RLIM_INFINITY)
3658 shf_puts("unlimited\n", shl_stdout);
3660 shprintf("%lu\n", (unsigned long)(val / l->factor));
3665 c_rename(const char **wp)
3671 if (wp[0] && !strcmp(wp[0], "--"))
3672 /* skip "--" (options separator) */
3675 /* check for exactly two arguments */
3676 if (wp[0] == NULL /* first argument */ ||
3677 wp[1] == NULL /* second argument */ ||
3678 wp[2] != NULL /* no further args please */)
3680 else if ((rv = rename(wp[0], wp[1])) != 0) {
3682 bi_errorf(Tf_sD_s, "failed", cstrerror(rv));
3689 c_realpath(const char **wp)
3696 if (wp[0] && !strcmp(wp[0], "--"))
3697 /* skip "--" (options separator) */
3700 /* check for exactly one argument */
3701 if (wp[0] == NULL || wp[1] != NULL)
3703 else if ((buf = do_realpath(wp[0])) == NULL) {
3705 bi_errorf(Tf_sD_s, wp[0], cstrerror(rv));
3706 if ((unsigned int)rv > 255)
3709 shprintf(Tf_sN, buf);
3718 c_cat(const char **wp)
3720 int fd = STDIN_FILENO, rv;
3722 const char *fn = "<stdin>";
3725 #define MKSH_CAT_BUFSIZ 4096
3727 /* parse options: POSIX demands we support "-u" as no-op */
3728 while ((rv = ksh_getopt(wp, &builtin_opt, "u")) != -1) {
3731 /* we already operate unbuffered */
3738 wp += builtin_opt.optind;
3741 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3742 bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
3747 opipe = block_pipe();
3754 else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
3755 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3760 while (/* CONSTCOND */ 1) {
3761 if ((n = blocking_read(fd, (cp = buf),
3762 MKSH_CAT_BUFSIZ)) == -1) {
3763 if (errno == EINTR) {
3764 restore_pipe(opipe);
3765 /* give the user a chance to ^C out */
3767 /* interrupted, try again */
3768 opipe = block_pipe();
3771 /* an error occured during reading */
3772 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3776 /* end of file reached */
3779 if ((w = write(STDOUT_FILENO, cp, n)) != -1) {
3784 if (errno == EINTR) {
3785 restore_pipe(opipe);
3786 /* give the user a chance to ^C out */
3788 /* interrupted, try again */
3789 opipe = block_pipe();
3792 if (errno == EPIPE) {
3793 /* fake receiving signel */
3794 rv = ksh_sigmask(SIGPIPE);
3796 /* an error occured during writing */
3797 bi_errorf(Tf_sD_s, "<stdout>",
3801 if (fd != STDIN_FILENO)
3806 if (fd != STDIN_FILENO)
3811 restore_pipe(opipe);
3818 c_sleep(const char **wp)
3825 if (wp[0] && !strcmp(wp[0], "--"))
3826 /* skip "--" (options separator) */
3829 if (!wp[0] || wp[1])
3831 else if (parse_usec(wp[0], &tv))
3832 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno), wp[0]);
3834 #ifndef MKSH_NOPROSPECTOFWORK
3835 sigset_t omask, bmask;
3837 /* block a number of signals from interrupting us, though */
3838 (void)sigemptyset(&bmask);
3839 (void)sigaddset(&bmask, SIGPIPE);
3840 (void)sigaddset(&bmask, SIGCHLD);
3842 (void)sigaddset(&bmask, SIGWINCH);
3845 (void)sigaddset(&bmask, SIGINFO);
3848 (void)sigaddset(&bmask, SIGUSR1);
3851 (void)sigaddset(&bmask, SIGUSR2);
3853 sigprocmask(SIG_BLOCK, &bmask, &omask);
3855 if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3857 * strictly speaking only for SIGALRM, but the
3858 * execution may be interrupted by other signals
3862 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
3863 #ifndef MKSH_NOPROSPECTOFWORK
3864 /* this will re-schedule signal delivery */
3865 sigprocmask(SIG_SETMASK, &omask, NULL);
3872 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
3874 c_suspend(const char **wp)
3876 if (wp[1] != NULL) {
3877 bi_errorf(Ttoo_many_args);
3881 /* Can't suspend an orphaned process group. */
3882 if (getpgid(kshppid) == getpgid(0) ||
3883 getsid(kshppid) != getsid(0)) {
3884 bi_errorf("can't suspend a login shell");