1 /* $OpenBSD: c_ksh.c,v 1.34 2013/12/17 16:37:05 deraadt Exp $ */
2 /* $OpenBSD: c_sh.c,v 1.44 2013/09/04 15:49:18 millert 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
9 * Thorsten Glaser <tg@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.256 2014/06/09 13:25:52 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 {"command", 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},
130 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
131 {"suspend", c_suspend},
134 {"*=times", c_times},
137 {T_typeset, c_typeset},
138 {"ulimit", c_ulimit},
140 {Tunalias, c_unalias},
143 {"whence", c_whence},
144 #ifndef MKSH_UNEMPLOYED
148 #ifndef MKSH_NO_CMDLINE_EDITING
154 #ifdef MKSH_PRINTF_BUILTIN
155 {"printf", c_printf},
161 /* alias to "true" for historical reasons */
162 {"domainname", c_true},
164 {NULL, (int (*)(const char **))NULL}
172 static const struct t_op {
202 static const struct t_op b_ops[] = {
220 static int test_oexpr(Test_env *, bool);
221 static int test_aexpr(Test_env *, bool);
222 static int test_nexpr(Test_env *, bool);
223 static int test_primary(Test_env *, bool);
224 static Test_op ptest_isa(Test_env *, Test_meta);
225 static const char *ptest_getopnd(Test_env *, Test_op, bool);
226 static void ptest_error(Test_env *, int, const char *);
227 static char *kill_fmt_entry(char *, size_t, unsigned int, const void *);
228 static void p_time(struct shf *, bool, long, int, int,
229 const char *, const char *);
232 c_pwd(const char **wp)
235 bool physical = tobool(Flag(FPHYSICAL));
236 char *p, *allocd = NULL;
238 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
249 wp += builtin_opt.optind;
252 bi_errorf("too many arguments");
255 p = current_wd[0] ? (physical ? allocd = do_realpath(current_wd) :
257 /* LINTED use of access */
258 if (p && access(p, R_OK) < 0)
260 if (!p && !(p = allocd = ksh_get_wd())) {
261 bi_errorf("%s: %s", "can't determine current directory",
266 afree(allocd, ATEMP);
270 static const char *s_ptr;
271 static int s_get(void);
272 static void s_put(int);
275 c_print(const char **wp)
277 #define PO_NL BIT(0) /* print newline */
278 #define PO_EXPAND BIT(1) /* expand backslash sequences */
279 #define PO_PMINUSMINUS BIT(2) /* print a -- argument */
280 #define PO_HIST BIT(3) /* print to history instead of stdout */
281 #define PO_COPROC BIT(4) /* printing to coprocess: block SIGPIPE */
283 int flags = PO_EXPAND | PO_NL;
284 const char *s, *emsg;
288 if (wp[0][0] == 'e') {
291 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
294 * MidnightBSD /bin/sh needs a BSD echo, that is,
295 * one that supports -e but does not enable it by
302 #ifndef MKSH_MIDNIGHTBSD01ASH_COMPAT
306 /* Debian Policy 10.4 compliant "echo" builtin */
307 if (*wp && !strcmp(*wp, "-n")) {
308 /* we recognise "-n" only as the first arg */
312 /* otherwise, we print everything as-is */
318 * a compromise between sysV and BSD echo commands:
319 * escape sequences are enabled by default, and -n,
320 * -e and -E are recognised if they appear in argu-
321 * ments with no illegal options (ie, echo -nq will
323 * Different from sysV echo since options are reco-
324 * gnised, different from BSD echo since escape se-
325 * quences are enabled by default.
328 while ((s = *wp) && *s == '-' && s[1]) {
335 nflags &= ~PO_EXPAND;
338 * bad option: don't use
339 * nflags, print argument
351 const char *opts = "Rnprsu,";
353 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1)
356 /* fake BSD echo command */
357 flags |= PO_PMINUSMINUS;
368 if ((fd = coproc_getfd(W_OK, &emsg)) < 0) {
369 bi_errorf("%s: %s", "-p", emsg);
380 if (!*(s = builtin_opt.optarg))
382 else if ((fd = check_fd(s, W_OK, &emsg)) < 0) {
383 bi_errorf("%s: %s: %s", "-u", s, emsg);
391 if (!(builtin_opt.info & GI_MINUSMINUS)) {
392 /* treat a lone - like -- */
393 if (wp[builtin_opt.optind] &&
394 ksh_isdash(wp[builtin_opt.optind]))
395 builtin_opt.optind++;
396 } else if (flags & PO_PMINUSMINUS)
397 builtin_opt.optind--;
398 wp += builtin_opt.optind;
401 Xinit(xs, xp, 128, ATEMP);
403 while (*wp != NULL) {
405 while ((c = *s++) != '\0') {
407 if ((flags & PO_EXPAND) && c == '\\') {
409 c = unbksl(false, s_get, s_put);
412 /* rejected by generic function */
413 switch ((c = *s++)) {
416 /* AT&T brain damage */
425 } else if ((unsigned int)c > 0xFF) {
426 /* generic function returned Unicode */
429 ts[utf_wctomb(ts, c - 0x100)] = 0;
430 for (c = 0; ts[c]; ++c)
443 if (flags & PO_HIST) {
445 histsave(&source->line, Xstring(xs, xp), true, false);
448 int len = Xlength(xs, xp);
452 * Ensure we aren't killed by a SIGPIPE while writing to
453 * a coprocess. AT&T ksh doesn't seem to do this (seems
454 * to just check that the co-process is alive which is
457 if (coproc.write >= 0 && coproc.write == fd) {
459 opipe = block_pipe();
461 for (s = Xstring(xs, xp); len > 0; ) {
462 if ((c = write(fd, s, len)) < 0) {
463 if (flags & PO_COPROC)
465 if (errno == EINTR) {
466 /* allow user to ^C out */
468 if (flags & PO_COPROC)
469 opipe = block_pipe();
477 if (flags & PO_COPROC)
491 s_put(int c MKSH_A_UNUSED)
497 c_whence(const char **wp)
501 bool pflag = false, vflag = false, Vflag = false;
502 int rv = 0, optc, fcflags;
503 bool iam_whence = wp[0][0] == 'w';
504 const char *opts = iam_whence ? "pv" : "pvV";
506 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1)
520 wp += builtin_opt.optind;
522 fcflags = FC_BI | FC_PATH | FC_FUNC;
524 /* Note that -p on its own is deal with in comexec() */
526 fcflags |= FC_DEFPATH;
528 * Convert command options to whence options - note that
529 * command -pV uses a different path search than whence -v
530 * or whence -pv. This should be considered a feature.
535 fcflags &= ~(FC_BI | FC_FUNC);
537 while ((vflag || rv == 0) && (id = *wp++) != NULL) {
541 if ((iam_whence || vflag) && !pflag)
542 tp = ktsearch(&keywords, id, h = hash(id));
544 tp = ktsearch(&aliases, id, h ? h : hash(id));
545 if (tp && !(tp->flag & ISSET))
549 tp = findcom(id, fcflags);
550 if (vflag || (tp->type != CALIAS && tp->type != CEXEC &&
551 tp->type != CTALIAS))
552 shf_puts(id, shl_stdout);
559 shf_puts(" is a", shl_stdout);
566 shf_puts(" reserved word", shl_stdout);
570 shprintf("n %s%s for ",
571 (tp->flag & EXPORT) ? "exported " : null,
573 if (!iam_whence && !vflag)
574 shprintf("%s %s=", Talias, id);
575 print_value_quoted(shl_stdout, tp->val.s);
579 if (tp->flag & EXPORT)
580 shf_puts("n exported", shl_stdout);
581 if (tp->flag & TRACE)
582 shf_puts(" traced", shl_stdout);
583 if (!(tp->flag & ISSET)) {
584 shf_puts(" undefined", shl_stdout);
586 shprintf(" (autoload from %s)",
589 shf_puts(T_function, shl_stdout);
595 (tp->flag & SPEC_BI) ? " special" : null,
600 if (tp->flag & ISSET) {
602 shf_puts(" is ", shl_stdout);
603 if (tp->type == CTALIAS)
604 shprintf("a tracked %s%s for ",
605 (tp->flag & EXPORT) ?
609 shf_puts(tp->val.s, shl_stdout);
612 shprintf(" %s\n", "not found");
617 shprintf("%s is *GOK*", id);
621 shf_putc('\n', shl_stdout);
626 /* Deal with command -vV - command -p dealt with in comexec() */
628 c_command(const char **wp)
631 * Let c_whence do the work. Note that c_command() must be
632 * a distinct function from c_whence() (tested in comexec()).
634 return (c_whence(wp));
637 /* typeset, global, export, and readonly */
638 static void c_typeset_vardump(struct tbl *, uint32_t, int, bool, bool);
639 static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
642 c_typeset(const char **wp)
645 uint32_t fset = 0, fclr = 0, flag;
646 int thing = 0, field = 0, base = 0, i;
649 const char *fieldstr = NULL, *basestr = NULL;
650 bool localv = false, func = false, pflag = false, istset = true;
651 enum namerefflag new_refflag = SRF_NOP;
669 /* called with 'typeset -' */
678 /* see comment below regarding possible opions */
679 opts = istset ? "L#R#UZ#afi#lnprtux" : "p";
681 builtin_opt.flags |= GF_PLUSOPT;
683 * AT&T ksh seems to have 0-9 as options which are multiplied
684 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
685 * sets right justify in a field of 12). This allows options
686 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
687 * does not allow the number to be specified as a separate argument
688 * Here, the number must follow the RLZi option, but is optional
689 * (see the # kludge in ksh_getopt()).
691 while ((i = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
696 fieldstr = builtin_opt.optarg;
700 fieldstr = builtin_opt.optarg;
704 * AT&T ksh uses u, but this conflicts with
705 * upper/lower case. If this option is changed,
706 * need to change the -U below as well
712 fieldstr = builtin_opt.optarg;
716 * this is supposed to set (-a) or unset (+a) the
717 * indexed array attribute; it does nothing on an
718 * existing regular string or indexed array though
726 basestr = builtin_opt.optarg;
732 new_refflag = (builtin_opt.info & GI_PLUS) ?
733 SRF_DISABLE : SRF_ENABLE;
735 /* export, readonly: POSIX -p flag */
737 /* typeset: show values as well */
749 /* upper case / autoload */
758 if (builtin_opt.info & GI_PLUS) {
769 if (fieldstr && !bi_getn(fieldstr, &field))
771 if (basestr && (!bi_getn(basestr, &base) || base < 1 || base > 36)) {
772 bi_errorf("%s: %s", "bad integer base", basestr);
776 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
777 (wp[builtin_opt.optind][0] == '-' ||
778 wp[builtin_opt.optind][0] == '+') &&
779 wp[builtin_opt.optind][1] == '\0') {
780 thing = wp[builtin_opt.optind][0];
781 builtin_opt.optind++;
784 if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
785 new_refflag != SRF_NOP)) {
786 bi_errorf("only -t, -u and -x options may be used with -f");
789 if (wp[builtin_opt.optind]) {
791 * Take care of exclusions.
792 * At this point, flags in fset are cleared in fclr and vice
793 * versa. This property should be preserved.
796 /* LCASEV has priority over UCASEV_AL */
799 /* LJUST has priority over RJUST */
801 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
807 * Setting these attributes clears the others, unless they
808 * are also set in this command
810 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
811 INTEGER | INT_U | INT_L)) || new_refflag != SRF_NOP)
812 fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
813 LCASEV | INTEGER | INT_U | INT_L);
815 if (new_refflag != SRF_NOP) {
816 fclr &= ~(ARRAY | ASSOC);
817 fset &= ~(ARRAY | ASSOC);
820 if (new_refflag == SRF_DISABLE)
824 /* set variables and attributes */
825 if (wp[builtin_opt.optind] &&
826 /* not "typeset -p varname" */
827 !(!func && pflag && !(fset | fclr))) {
833 for (i = builtin_opt.optind; wp[i]; i++) {
835 f = findfunc(wp[i], hash(wp[i]),
836 tobool(fset & UCASEV_AL));
838 /* AT&T ksh does ++rv: bogus */
846 fpFUNCTf(shl_stdout, 0,
847 tobool(f->flag & FKSH),
849 shf_putc('\n', shl_stdout);
851 } else if (!typeset(wp[i], fset, fclr, field, base)) {
852 bi_errorf("%s: %s", wp[i], "is not an identifier");
859 /* list variables and attributes */
861 /* no difference at this point.. */
864 for (l = e->loc; l; l = l->next) {
865 for (p = ktsort(&l->funs); (vp = *p++); ) {
866 if (flag && (vp->flag & flag) == 0)
869 fpFUNCTf(shl_stdout, 0,
870 tobool(vp->flag & FKSH),
871 vp->name, vp->val.t);
873 shf_puts(vp->name, shl_stdout);
874 shf_putc('\n', shl_stdout);
877 } else if (wp[builtin_opt.optind]) {
878 for (i = builtin_opt.optind; wp[i]; i++) {
879 varsearch(e->loc, &vp, wp[i], hash(wp[i]));
880 c_typeset_vardump(vp, flag, thing, pflag, istset);
883 c_typeset_vardump_recursive(e->loc, flag, thing, pflag, istset);
888 c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
889 bool pflag, bool istset)
891 struct tbl **blockvars, *vp;
894 c_typeset_vardump_recursive(l->next, flag, thing, pflag, istset);
895 blockvars = ktsort(&l->vars);
896 while ((vp = *blockvars++))
897 c_typeset_vardump(vp, flag, thing, pflag, istset);
898 /*XXX doesn’t this leak? */
902 c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, bool pflag,
913 * See if the parameter is set (for arrays, if any
916 for (tvp = vp; tvp; tvp = tvp->u.array)
917 if (tvp->flag & ISSET) {
923 * Check attributes - note that all array elements
924 * have (should have?) the same attributes, so checking
925 * the first is sufficient.
927 * Report an unset param only if the user has
928 * explicitly given it some attribute (like export);
929 * otherwise, after "echo $FOO", we would report FOO...
931 if (!any_set && !(vp->flag & USERATTRIB))
933 if (flag && (vp->flag & flag) == 0)
935 if (!(vp->flag & ARRAY))
936 /* optimise later conditionals */
940 * Ignore array elements that aren't set unless there
941 * are no set elements, in which case the first is
944 if (any_set && !(vp->flag & ISSET))
947 if (!thing && !flag) {
949 shprintf("%s %s %s\n", Tset, "-A", vp->name);
953 * AT&T ksh prints things like export, integer,
954 * leftadj, zerofill, etc., but POSIX says must
955 * be suitable for re-entry...
957 shprintf("%s %s", Ttypeset, "");
958 if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
959 shprintf("%s ", "-n");
960 if ((vp->flag & INTEGER))
961 shprintf("%s ", "-i");
962 if ((vp->flag & EXPORT))
963 shprintf("%s ", "-x");
964 if ((vp->flag & RDONLY))
965 shprintf("%s ", "-r");
966 if ((vp->flag & TRACE))
967 shprintf("%s ", "-t");
968 if ((vp->flag & LJUST))
969 shprintf("-L%d ", vp->u2.field);
970 if ((vp->flag & RJUST))
971 shprintf("-R%d ", vp->u2.field);
972 if ((vp->flag & ZEROFIL))
973 shprintf("%s ", "-Z");
974 if ((vp->flag & LCASEV))
975 shprintf("%s ", "-l");
976 if ((vp->flag & UCASEV_AL))
977 shprintf("%s ", "-u");
978 if ((vp->flag & INT_U))
979 shprintf("%s ", "-U");
981 shprintf("%s %s", istset ? Ttypeset :
982 (flag & EXPORT) ? Texport : Treadonly, "");
985 shprintf("%s[%lu]", vp->name, arrayindex(vp));
987 shf_puts(vp->name, shl_stdout);
988 if ((!thing && !flag && pflag) ||
989 (thing == '-' && (vp->flag & ISSET))) {
991 shf_putc('=', shl_stdout);
992 /* AT&T ksh can't have justified integers... */
993 if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
994 shf_puts(s, shl_stdout);
996 print_value_quoted(shl_stdout, s);
998 shf_putc('\n', shl_stdout);
1001 * Only report first 'element' of an array with
1006 } while ((vp = vp->u.array));
1010 c_alias(const char **wp)
1012 struct table *t = &aliases;
1013 int rv = 0, prefix = 0;
1014 bool rflag = false, tflag, Uflag = false, pflag = false;
1018 builtin_opt.flags |= GF_PLUSOPT;
1019 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
1020 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
1024 t = NULL; /* fix "alias -dt" */
1040 * kludge for tracked alias initialization
1041 * (don't do a path search, just make an entry)
1056 wp += builtin_opt.optind;
1058 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
1059 (wp[0][0] == '-' || wp[0][0] == '+') && wp[0][1] == '\0') {
1064 tflag = t == &taliases;
1066 /* "hash -r" means reset all the tracked aliases.. */
1068 static const char *args[] = {
1069 Tunalias, "-ta", NULL
1072 if (!tflag || *wp) {
1073 shprintf("%s: -r flag can only be used with -t"
1074 " and without arguments\n", Talias);
1077 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1078 return (c_unalias(args));
1082 struct tbl *ap, **p;
1084 for (p = ktsort(t); (ap = *p++) != NULL; )
1085 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
1087 shprintf("%s ", Talias);
1088 shf_puts(ap->name, shl_stdout);
1089 if (prefix != '+') {
1090 shf_putc('=', shl_stdout);
1091 print_value_quoted(shl_stdout, ap->val.s);
1093 shf_putc('\n', shl_stdout);
1097 for (; *wp != NULL; wp++) {
1098 const char *alias = *wp, *val, *newval;
1099 char *xalias = NULL;
1103 if ((val = cstrchr(alias, '='))) {
1104 strndupx(xalias, alias, val++ - alias, ATEMP);
1108 if (val == NULL && !tflag && !xflag) {
1109 ap = ktsearch(t, alias, h);
1110 if (ap != NULL && (ap->flag&ISSET)) {
1112 shprintf("%s ", Talias);
1113 shf_puts(ap->name, shl_stdout);
1114 if (prefix != '+') {
1115 shf_putc('=', shl_stdout);
1116 print_value_quoted(shl_stdout, ap->val.s);
1118 shf_putc('\n', shl_stdout);
1120 shprintf("%s %s %s\n", alias, Talias,
1126 ap = ktenter(t, alias, h);
1127 ap->type = tflag ? CTALIAS : CALIAS;
1128 /* Are we setting the value or just some flags? */
1129 if ((val && !tflag) || (!val && tflag && !Uflag)) {
1130 if (ap->flag&ALLOC) {
1131 ap->flag &= ~(ALLOC|ISSET);
1132 afree(ap->val.s, APERM);
1134 /* ignore values for -t (AT&T ksh does this) */
1136 search_path(alias, path, X_OK, NULL) :
1139 strdupx(ap->val.s, newval, APERM);
1140 ap->flag |= ALLOC|ISSET;
1144 ap->flag |= DEFINED;
1149 afree(xalias, ATEMP);
1156 c_unalias(const char **wp)
1158 struct table *t = &aliases;
1163 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
1170 /* fix "unalias -dt" */
1186 wp += builtin_opt.optind;
1188 for (; *wp != NULL; wp++) {
1189 ap = ktsearch(t, *wp, hash(*wp));
1195 if (ap->flag&ALLOC) {
1196 ap->flag &= ~(ALLOC|ISSET);
1197 afree(ap->val.s, APERM);
1199 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1205 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
1206 if (ap->flag&ALLOC) {
1207 ap->flag &= ~(ALLOC|ISSET);
1208 afree(ap->val.s, APERM);
1210 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1218 c_let(const char **wp)
1224 /* AT&T ksh does this */
1225 bi_errorf("no arguments");
1227 for (wp++; *wp; wp++)
1228 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
1229 /* distinguish error from zero result */
1238 c_jobs(const char **wp)
1240 int optc, flag = 0, nflag = 0, rv = 0;
1242 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1254 /* debugging: print zombies */
1260 wp += builtin_opt.optind;
1262 if (j_jobs(NULL, flag, nflag))
1266 if (j_jobs(*wp, flag, nflag))
1272 #ifndef MKSH_UNEMPLOYED
1274 c_fgbg(const char **wp)
1276 bool bg = strcmp(*wp, "bg") == 0;
1279 if (!Flag(FMONITOR)) {
1280 bi_errorf("job control not enabled");
1283 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1285 wp += builtin_opt.optind;
1288 rv = j_resume(*wp, bg);
1290 rv = j_resume("%%", bg);
1291 return (bg ? 0 : rv);
1295 /* format a single kill item */
1297 kill_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1299 const struct kill_info *ki = (const struct kill_info *)arg;
1302 shf_snprintf(buf, buflen, "%*u %*s %s",
1304 ki->name_width, sigtraps[i].name,
1310 c_kill(const char **wp)
1317 /* assume old style options if -digits or -UPPERCASE */
1318 if ((p = wp[1]) && *p == '-' && (ksh_isdigit(p[1]) ||
1319 ksh_isupper(p[1]))) {
1320 if (!(t = gettrap(p + 1, false))) {
1321 bi_errorf("bad signal '%s'", p + 1);
1324 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1328 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1334 if (!(t = gettrap(builtin_opt.optarg, true))) {
1335 bi_errorf("bad signal '%s'",
1336 builtin_opt.optarg);
1343 i = builtin_opt.optind;
1345 if ((lflag && t) || (!wp[i] && !lflag)) {
1347 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1348 " { job | pid | pgrp } ...\n"
1349 "\tkill -l [exit_status ...]\n", shl_out);
1357 for (; wp[i]; i++) {
1358 if (!bi_getn(wp[i], &n))
1361 if (n > 128 && n < 128 + NSIG)
1364 if (n > 0 && n < NSIG)
1365 shprintf("%s\n", sigtraps[n].name);
1367 shprintf("%d\n", n);
1370 ssize_t w, mess_cols, mess_octs;
1372 struct kill_info ki;
1374 for (j = NSIG, ki.num_width = 1; j >= 10; j /= 10)
1376 ki.name_width = mess_cols = mess_octs = 0;
1377 for (j = 0; j < NSIG; j++) {
1378 w = strlen(sigtraps[j].name);
1379 if (w > ki.name_width)
1381 w = strlen(sigtraps[j].mess);
1384 w = utf_mbswidth(sigtraps[j].mess);
1389 print_columns(shl_stdout, (unsigned int)(NSIG - 1),
1390 kill_fmt_entry, (void *)&ki,
1391 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1392 ki.num_width + 1 + ki.name_width + 1 + mess_cols,
1398 sig = t ? t->signal : SIGTERM;
1399 for (; (p = wp[i]); i++) {
1403 } else if (!getn(p, &n)) {
1404 bi_errorf("%s: %s", p,
1405 "arguments must be jobs or process IDs");
1408 if (mksh_kill(n, sig) < 0) {
1409 bi_errorf("%s: %s", p, cstrerror(errno));
1418 getopts_reset(int val)
1421 ksh_getopt_reset(&user_opt, GF_NONAME | GF_PLUSOPT);
1422 user_opt.optind = user_opt.uoptind = val;
1427 c_getopts(const char **wp)
1430 const char *opts, *var;
1432 struct tbl *vq, *voptarg;
1434 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1436 wp += builtin_opt.optind;
1440 bi_errorf("missing %s argument", "options");
1446 bi_errorf("missing %s argument", "name");
1449 if (!*var || *skip_varname(var, true)) {
1450 bi_errorf("%s: %s", var, "is not an identifier");
1454 if (e->loc->next == NULL) {
1455 internal_warningf("%s: %s", "c_getopts", "no argv");
1458 /* Which arguments are we parsing... */
1460 wp = e->loc->next->argv;
1462 *--wp = e->loc->next->argv[0];
1464 /* Check that our saved state won't cause a core dump... */
1465 for (argc = 0; wp[argc]; argc++)
1467 if (user_opt.optind > argc ||
1469 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1470 bi_errorf("arguments changed since last call");
1474 user_opt.optarg = NULL;
1475 optc = ksh_getopt(wp, &user_opt, opts);
1477 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1483 * POSIX says var is set to ? at end-of-options, AT&T ksh
1484 * sets it to null - we go with POSIX...
1486 buf[0] = optc < 0 ? '?' : optc;
1490 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1491 user_opt.uoptind = user_opt.optind;
1493 voptarg = global("OPTARG");
1494 /* AT&T ksh clears ro and int */
1495 voptarg->flag &= ~RDONLY;
1496 /* Paranoia: ensure no bizarre results. */
1497 if (voptarg->flag & INTEGER)
1498 typeset("OPTARG", 0, INTEGER, 0, 0);
1499 if (user_opt.optarg == NULL)
1502 /* This can't fail (have cleared readonly/integer) */
1503 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1508 /* Error message already printed (integer, readonly) */
1509 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1512 typeset(var, EXPORT, 0, 0, 0);
1514 return (optc < 0 ? 1 : rv);
1517 #ifndef MKSH_NO_CMDLINE_EDITING
1519 c_bind(const char **wp)
1529 while ((optc = ksh_getopt(wp, &builtin_opt,
1548 wp += builtin_opt.optind;
1552 rv = x_bind(NULL, NULL,
1558 for (; *wp != NULL; wp++) {
1559 if ((cp = cstrchr(*wp, '=')) == NULL)
1562 strdupx(up, *wp, ATEMP);
1563 up[cp++ - *wp] = '\0';
1565 if (x_bind(up ? up : *wp, cp,
1579 c_shift(const char **wp)
1581 struct block *l = e->loc;
1586 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1588 arg = wp[builtin_opt.optind];
1591 evaluate(arg, &val, KSH_UNWIND_ERROR, false);
1596 bi_errorf("%s: %s", arg, "bad number");
1600 bi_errorf("nothing to shift");
1603 l->argv[n] = l->argv[0];
1610 c_umask(const char **wp)
1614 bool symbolic = false;
1617 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1625 cp = wp[builtin_opt.optind];
1627 old_umask = umask((mode_t)0);
1633 old_umask = ~old_umask;
1635 for (i = 0; i < 3; i++) {
1638 for (j = 0; j < 3; j++)
1639 if (old_umask & (1 << (8 - (3*i + j))))
1644 shprintf("%s\n", buf);
1646 shprintf("%#3.3o\n", (unsigned int)old_umask);
1650 if (ksh_isdigit(*cp)) {
1651 for (new_umask = 0; *cp >= '0' && *cp <= '7'; cp++)
1652 new_umask = new_umask * 8 + (*cp - '0');
1654 bi_errorf("bad number");
1658 /* symbolic format */
1659 int positions, new_val;
1662 old_umask = umask((mode_t)0);
1663 /* in case of error */
1665 old_umask = ~old_umask;
1666 new_umask = old_umask;
1669 while (*cp && vstrchr("augo", *cp))
1687 if (!vstrchr("=+-", op = *cp))
1691 while (*cp && vstrchr("rwxugoXs", *cp))
1693 case 'r': new_val |= 04; break;
1694 case 'w': new_val |= 02; break;
1695 case 'x': new_val |= 01; break;
1697 new_val |= old_umask >> 6;
1700 new_val |= old_umask >> 3;
1703 new_val |= old_umask >> 0;
1706 if (old_umask & 0111)
1713 new_val = (new_val & 07) * positions;
1716 new_umask &= ~new_val;
1719 new_umask = new_val |
1720 (new_umask & ~(positions * 07));
1723 new_umask |= new_val;
1728 } else if (!vstrchr("=+-", *cp))
1732 bi_errorf("bad mask");
1735 new_umask = ~new_umask;
1743 c_dot(const char **wp)
1745 const char *file, *cp, **argv;
1746 int argc, i, errcode;
1748 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1751 if ((cp = wp[builtin_opt.optind]) == NULL) {
1752 bi_errorf("missing argument");
1755 if ((file = search_path(cp, path, R_OK, &errcode)) == NULL) {
1756 bi_errorf("%s: %s", cp, cstrerror(errcode));
1760 /* Set positional parameters? */
1761 if (wp[builtin_opt.optind + 1]) {
1762 argv = wp + builtin_opt.optind;
1764 argv[0] = e->loc->argv[0];
1765 for (argc = 0; argv[argc + 1]; argc++)
1771 if ((i = include(file, argc, argv, false)) < 0) {
1772 /* should not happen */
1773 bi_errorf("%s: %s", cp, cstrerror(errno));
1780 c_wait(const char **wp)
1784 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1786 wp += builtin_opt.optind;
1788 while (waitfor(NULL, &sig) >= 0)
1793 rv = waitfor(*wp, &sig);
1795 /* magic exit code: bad job-id */
1796 rv = sig ? sig : 127;
1801 static char REPLY[] = "REPLY";
1803 c_read(const char **wp)
1805 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1806 int c, fd = 0, rv = 0, lastparm = 0;
1807 bool savehist = false, intoarray = false, aschars = false;
1808 bool rawmode = false, expanding = false;
1809 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1811 size_t bytesleft = 128, bytesread;
1812 struct tbl *vp /* FU gcc */ = NULL, *vq;
1813 char *cp, *allocd = NULL, *xp;
1816 ptrdiff_t xsave = 0;
1818 bool restore_tios = false;
1820 bool hastimeout = false;
1821 struct timeval tv, tvlim;
1822 #define c_read_opts "Aad:N:n:prst:u,"
1824 #define c_read_opts "Aad:N:n:prsu,"
1827 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1836 delim = builtin_opt.optarg[0];
1840 readmode = c == 'N' ? BYTES : UPTO;
1841 if (!bi_getn(builtin_opt.optarg, &c))
1847 bytesleft = (unsigned int)c;
1850 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1851 bi_errorf("%s: %s", "-p", ccp);
1863 if (parse_usec(builtin_opt.optarg, &tv)) {
1864 bi_errorf("%s: %s '%s'", Tsynerr, cstrerror(errno),
1865 builtin_opt.optarg);
1872 if (!builtin_opt.optarg[0])
1874 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1875 bi_errorf("%s: %s: %s", "-u", builtin_opt.optarg, ccp);
1882 wp += builtin_opt.optind;
1886 if (intoarray && wp[1] != NULL) {
1887 bi_errorf("too many arguments");
1891 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1892 strdupx(allocd, *wp, ATEMP);
1893 allocd[ccp - *wp] = '\0';
1897 * AT&T ksh says it prints prompt on fd if it's open
1898 * for writing and is a tty, but it doesn't do it
1899 * (it also doesn't check the interactive flag,
1900 * as is indicated in the Korn Shell book).
1902 shf_puts(ccp + 1, shl_out);
1907 Xinit(xs, xp, bytesleft, ATEMP);
1909 if (readmode == LINES)
1911 else if (isatty(fd)) {
1912 x_mkraw(fd, &tios, true);
1913 restore_tios = true;
1919 timeradd(&tvlim, &tv, &tvlim);
1929 FD_SET((unsigned int)fd, &fdset);
1931 timersub(&tvlim, &tv, &tv);
1932 if (tv.tv_sec < 0) {
1933 /* timeout expired globally */
1938 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
1942 /* timeout expired for this call */
1946 bi_errorf("%s: %s", Tselect, cstrerror(errno));
1953 bytesread = blocking_read(fd, xp, bytesleft);
1954 if (bytesread == (size_t)-1) {
1956 if (errno == EINTR && fatal_trap_check()) {
1958 * Was the offending signal one that would
1959 * normally kill a process? If so, pretend
1960 * the read was killed.
1965 /* just ignore the signal */
1966 goto c_read_readloop;
1971 if (bytesread == 0) {
1972 /* end of file reached */
1974 goto c_read_readdone;
1977 XcheckN(xs, xp, bytesleft);
1982 /* end of file reached */
1985 goto c_read_readdone;
1988 if (bytesread == 0) {
1989 /* end of file reached */
1991 xp = Xstring(xs, xp);
1992 goto c_read_readdone;
1995 if ((bytesleft -= bytesread) == 0)
1996 goto c_read_readdone;
1999 if (bytesread == 0) {
2000 /* end of file reached */
2002 goto c_read_readdone;
2004 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
2005 /* skip any read NULs unless delimiter */
2011 if (Flag(FTALKING_I) && isatty(fd)) {
2013 * set prompt in case this is
2014 * called from .profile or $ENV
2016 set_prompt(PS2, NULL);
2019 /* drop the backslash */
2021 /* and the delimiter */
2024 } else if (c == delim) {
2025 goto c_read_readdone;
2026 } else if (!rawmode && c == '\\') {
2033 goto c_read_readloop;
2036 bytesread = Xlength(xs, xp);
2040 * state: we finished reading the input and NUL terminated it
2041 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
2042 * rv = 1 if EOF, 0 otherwise (errors handled already)
2046 /* clean up coprocess if needed, on EOF */
2047 coproc_read_close(fd);
2048 if (readmode == READALL)
2049 /* EOF is no error here */
2054 histsave(&source->line, Xstring(xs, xp), true, false);
2056 ccp = cp = Xclose(xs, xp);
2058 XinitN(xs, 128, ATEMP);
2061 if (vp->flag & RDONLY) {
2063 bi_errorf("read-only: %s", *wp);
2069 /* exporting an array is currently pointless */
2071 /* counter for array index */
2075 /* skip initial IFS whitespace */
2076 while (bytesread && is_ifsws(*ccp)) {
2080 /* trim trailing IFS whitespace */
2081 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
2086 xp = Xstring(xs, xp);
2087 /* generate next word */
2091 goto c_read_splitdone;
2092 /* zero out next parameters */
2093 goto c_read_gotword;
2098 bytesleft = utf_ptradj(ccp);
2099 while (bytesleft && bytesread) {
2104 if (xp[-1] == '\0') {
2108 goto c_read_gotword;
2111 if (!intoarray && wp[1] == NULL)
2115 /* copy until IFS character */
2122 goto c_read_splitcopy;
2123 } else if (ctype(ch, C_IFS)) {
2125 } else if (!rawmode && ch == '\\') {
2135 xsave = Xsavepos(xs, xp);
2136 /* copy word delimiter: IFSWS+IFS,IFSWS */
2141 if (!ctype(ch, C_IFS))
2147 if (!ctype(ch, C_IFSWS))
2150 while (bytesread && is_ifsws(*ccp)) {
2156 /* if no more parameters, rinse and repeat */
2157 if (lastparm && bytesread) {
2159 goto c_read_splitlast;
2161 /* get rid of the delimiter unless we pack the rest */
2163 xp = Xrestpos(xs, xp, xsave);
2167 vq = arraysearch(vp, c++);
2170 /* must be checked before exporting */
2171 if (vq->flag & RDONLY)
2172 goto c_read_splitro;
2174 typeset(*wp, EXPORT, 0, 0, 0);
2176 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
2177 goto c_read_spliterr;
2179 setint_v(vq, vq, false);
2180 /* protect from UTFMODE changes */
2183 if (intoarray || *++wp != NULL)
2184 goto c_read_splitloop;
2191 afree(allocd, ATEMP);
2194 mksh_tcset(fd, &tios);
2200 c_eval(const char **wp)
2202 struct source *s, *saves = source;
2203 unsigned char savef;
2206 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2208 s = pushs(SWORDS, ATEMP);
2209 s->u.strv = wp + builtin_opt.optind;
2212 * The following code handles the case where the command is
2213 * empty due to failed command substitution, for example by
2215 * This has historically returned 1 by AT&T ksh88. In this
2216 * case, shell() will not set or change exstat because the
2217 * compiled tree is empty, so it will use the value we pass
2218 * from subst_exstat, which is cleared in execute(), so it
2219 * should have been 0 if there were no substitutions.
2221 * POSIX however says we don't do this, even though it is
2222 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2223 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2225 * 2.9.1: Simple Commands
2226 * ... If there is a command name, execution shall
2227 * continue as described in 2.9.1.1 [Command Search
2228 * and Execution]. If there is no command name, but
2229 * the command contained a command substitution, the
2230 * command shall complete with the exit status of the
2231 * last command substitution performed.
2232 * 2.9.1.1: Command Search and Execution
2233 * (1) a. If the command name matches the name of a
2234 * special built-in utility, that special built-in
2235 * utility shall be invoked.
2237 * If there are no arguments, or only null arguments,
2238 * eval shall return a zero exit status; ...
2240 /* AT&T ksh88: use subst_exstat */
2241 /* exstat = subst_exstat; */
2242 /* SUSv4: OR with a high value never written otherwise */
2245 savef = Flag(FERREXIT);
2246 Flag(FERREXIT) |= 0x80;
2247 rv = shell(s, false);
2248 Flag(FERREXIT) = savef;
2251 if (exstat & 0x4000)
2252 /* detect old exstat, use 0 in that case */
2258 c_trap(const char **wp)
2264 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2266 wp += builtin_opt.optind;
2269 for (p = sigtraps, i = NSIG + 1; --i >= 0; p++)
2270 if (p->trap != NULL) {
2271 shf_puts("trap -- ", shl_stdout);
2272 print_value_quoted(shl_stdout, p->trap);
2273 shprintf(" %s\n", p->name);
2279 * Use case sensitive lookup for first arg so the
2280 * command 'exit' isn't confused with the pseudo-signal
2284 s = (gettrap(*wp, false) == NULL) ? *wp++ : NULL;
2285 if (s != NULL && s[0] == '-' && s[1] == '\0')
2288 /* set/clear traps */
2291 if ((p = gettrap(*wp++, true)) == NULL) {
2292 warningf(true, "%s: %s '%s'", builtin_argv0,
2293 "bad signal", wp[-1]);
2301 c_exitreturn(const char **wp)
2306 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2307 goto c_exitreturn_err;
2308 arg = wp[builtin_opt.optind];
2311 if (!getn(arg, &n)) {
2313 warningf(true, "%s: %s", arg, "bad number");
2316 } else if (trap_exstat != -1)
2317 exstat = trap_exstat;
2318 if (wp[0][0] == 'r') {
2323 * need to tell if this is exit or return so trap exit will
2324 * work right (POSIX)
2326 for (ep = e; ep; ep = ep->oenv)
2327 if (STOP_RETURN(ep->type)) {
2333 if (how == LEXIT && !really_exit && j_stopped_running()) {
2338 /* get rid of any i/o redirections */
2348 c_brkcont(const char **wp)
2352 struct env *ep, *last_ep = NULL;
2355 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2357 arg = wp[builtin_opt.optind];
2361 else if (!bi_getn(arg, &n))
2364 /* AT&T ksh does this for non-interactive shells only - weird */
2365 bi_errorf("%s: %s", arg, "bad value");
2368 quit = (unsigned int)n;
2370 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2371 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2372 if (ep->type == E_LOOP) {
2375 ep->flags |= EF_BRKCONT_PASS;
2381 * AT&T ksh doesn't print a message - just does what it
2382 * can. We print a message 'cause it helps in debugging
2383 * scripts, but don't generate an error (ie, keep going).
2385 if ((unsigned int)n == quit) {
2386 warningf(true, "%s: %s %s", wp[0], "can't", wp[0]);
2390 * POSIX says if n is too big, the last enclosing loop
2391 * shall be used. Doesn't say to print an error but we
2392 * do anyway 'cause the user messed up.
2395 last_ep->flags &= ~EF_BRKCONT_PASS;
2396 warningf(true, "%s: can only %s %u level(s)",
2397 wp[0], wp[0], (unsigned int)n - quit);
2400 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2408 c_set(const char **wp)
2412 struct block *l = e->loc;
2415 if (wp[1] == NULL) {
2416 static const char *args[] = { Tset, "-", NULL };
2417 return (c_typeset(args));
2420 argi = parse_args(wp, OF_SET, &setargs);
2429 while (*++wp != NULL)
2430 strdupx(*wp, *wp, &l->area);
2431 l->argc = wp - owp - 1;
2432 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2433 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2437 * POSIX says set exit status is 0, but old scripts that use
2438 * getopt(1) use the construct
2439 * set -- $(getopt ab:c "$@")
2440 * which assumes the exit value set will be that of the $()
2441 * (subst_exstat is cleared in execute() so that it will be 0
2442 * if there are no command substitutions).
2444 #ifdef MKSH_LEGACY_MODE
2445 /* traditional behaviour, unless set -o posix */
2446 return (Flag(FPOSIX) ? 0 : subst_exstat);
2448 /* conformant behaviour, unless set -o sh +o posix */
2449 return (Flag(FSH) && !Flag(FPOSIX) ? subst_exstat : 0);
2454 c_unset(const char **wp)
2458 bool unset_var = true;
2460 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2469 /*XXX not reached due to GF_ERROR */
2472 wp += builtin_opt.optind;
2473 for (; (id = *wp) != NULL; wp++)
2475 /* unset variable */
2481 if (n > 3 && id[n-3] == '[' && id[n-2] == '*' &&
2483 strndupx(cp, id, n - 3, ATEMP);
2487 optc = vstrchr(id, '[') ? 0 : 1;
2492 if ((vp->flag&RDONLY)) {
2493 warningf(true, "read-only: %s", vp->name);
2498 /* unset function */
2504 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2505 const char *prefix, const char *suffix)
2509 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2510 tv_sec, tv_usec, suffix);
2512 shf_fprintf(shf, "%s%*ldm%d.%02ds%s", prefix, width,
2513 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2517 c_times(const char **wp MKSH_A_UNUSED)
2519 struct rusage usage;
2521 getrusage(RUSAGE_SELF, &usage);
2522 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2523 usage.ru_utime.tv_usec, 0, null, " ");
2524 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2525 usage.ru_stime.tv_usec, 0, null, "\n");
2527 getrusage(RUSAGE_CHILDREN, &usage);
2528 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2529 usage.ru_utime.tv_usec, 0, null, " ");
2530 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2531 usage.ru_stime.tv_usec, 0, null, "\n");
2537 * time pipeline (really a statement, not a built-in command)
2540 timex(struct op *t, int f, volatile int *xerrok)
2542 #define TF_NOARGS BIT(0)
2543 #define TF_NOREAL BIT(1) /* don't report real time */
2544 #define TF_POSIX BIT(2) /* report in POSIX format */
2546 struct rusage ru0, ru1, cru0, cru1;
2547 struct timeval usrtime, systime, tv0, tv1;
2550 getrusage(RUSAGE_SELF, &ru0);
2551 getrusage(RUSAGE_CHILDREN, &cru0);
2554 * Two ways of getting cpu usage of a command: just use t0
2555 * and t1 (which will get cpu usage from other jobs that
2556 * finish while we are executing t->left), or get the
2557 * cpu usage of t->left. AT&T ksh does the former, while
2558 * pdksh tries to do the later (the j_usrtime hack doesn't
2559 * really work as it only counts the last job).
2561 timerclear(&j_usrtime);
2562 timerclear(&j_systime);
2563 rv = execute(t->left, f | XTIME, xerrok);
2564 if (t->left->type == TCOM)
2565 tf |= t->left->str[0];
2567 getrusage(RUSAGE_SELF, &ru1);
2568 getrusage(RUSAGE_CHILDREN, &cru1);
2572 if (tf & TF_NOARGS) {
2573 /* ksh93 - report shell times (shell+kids) */
2575 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2576 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2578 timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
2579 timeradd(&usrtime, &j_usrtime, &usrtime);
2580 timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
2581 timeradd(&systime, &j_systime, &systime);
2584 if (!(tf & TF_NOREAL)) {
2585 timersub(&tv1, &tv0, &tv1);
2587 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2590 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2594 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2597 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2600 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2603 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2604 5, null, " system\n");
2611 timex_hook(struct op *t, char **volatile *app)
2617 ksh_getopt_reset(&opt, 0);
2618 /* start at the start */
2620 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2623 t->str[0] |= TF_POSIX;
2626 errorf("time: -%s %s", opt.optarg,
2629 errorf("time: -%s %s", opt.optarg,
2630 "requires an argument");
2632 /* Copy command words down over options. */
2633 if (opt.optind != 0) {
2634 for (i = 0; i < opt.optind; i++)
2635 afree(wp[i], ATEMP);
2636 for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
2640 t->str[0] |= TF_NOARGS;
2644 /* exec with no args - args case is taken care of in comexec() */
2646 c_exec(const char **wp MKSH_A_UNUSED)
2650 /* make sure redirects stay in place */
2651 if (e->savefd != NULL) {
2652 for (i = 0; i < NUFILE; i++) {
2653 if (e->savefd[i] > 0)
2654 close(e->savefd[i]);
2655 #ifndef MKSH_LEGACY_MODE
2657 * keep all file descriptors > 2 private for ksh,
2658 * but not for POSIX or legacy/kludge sh
2660 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2662 fcntl(i, F_SETFD, FD_CLOEXEC);
2672 c_mknod(const char **wp)
2674 int argc, optc, rv = 0;
2675 bool ismkfifo = false;
2678 mode_t mode = 0, oldmode = 0;
2680 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2683 set = setmode(builtin_opt.optarg);
2685 bi_errorf("invalid file mode");
2688 mode = getmode(set, (mode_t)(DEFFILEMODE));
2689 free_ossetmode(set);
2695 argv = &wp[builtin_opt.optind];
2696 if (argv[0] == NULL)
2698 for (argc = 0; argv[argc]; argc++)
2700 if (argc == 2 && argv[1][0] == 'p')
2702 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2706 oldmode = umask((mode_t)0);
2710 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2711 (argv[1][0] == 'c') ? S_IFCHR : 0;
2714 unsigned long majnum, minnum;
2718 majnum = strtoul(argv[2], &c, 0);
2719 if ((c == argv[2]) || (*c != '\0')) {
2720 bi_errorf("non-numeric %s %s '%s'", "device", "major", argv[2]);
2723 minnum = strtoul(argv[3], &c, 0);
2724 if ((c == argv[3]) || (*c != '\0')) {
2725 bi_errorf("non-numeric %s %s '%s'", "device", "minor", argv[3]);
2728 dv = makedev(majnum, minnum);
2729 if ((unsigned long)(major(dv)) != majnum) {
2730 bi_errorf("%s %s too large: %lu", "device", "major", majnum);
2733 if ((unsigned long)(minor(dv)) != minnum) {
2734 bi_errorf("%s %s too large: %lu", "device", "minor", minnum);
2737 if (mknod(argv[0], mode, dv))
2738 goto c_mknod_failed;
2739 } else if (mkfifo(argv[0], mode)) {
2741 bi_errorf("%s: %s", argv[0], cstrerror(errno));
2750 bi_errorf("%s: %s", "usage", "mknod [-m mode] name b|c major minor");
2751 bi_errorf("%s: %s", "usage", "mknod [-m mode] name p");
2757 test(1) roughly accepts the following grammar:
2758 oexpr ::= aexpr | aexpr "-o" oexpr ;
2759 aexpr ::= nexpr | nexpr "-a" aexpr ;
2760 nexpr ::= primary | "!" nexpr ;
2761 primary ::= unary-operator operand
2762 | operand binary-operator operand
2767 unary-operator ::= "-a"|"-r"|"-w"|"-x"|"-e"|"-f"|"-d"|"-c"|"-b"|"-p"|
2768 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|
2769 "-L"|"-h"|"-S"|"-H";
2771 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
2773 "<"|">" # rules used for [[ ... ]] expressions
2775 operand ::= <anything>
2778 /* POSIX says > 1 for errors */
2779 #define T_ERR_EXIT 2
2782 c_test(const char **wp)
2784 int argc, rv, invert = 0;
2787 const char *lhs, **swp;
2791 te.getopnd = ptest_getopnd;
2792 te.eval = test_eval;
2793 te.error = ptest_error;
2795 for (argc = 0; wp[argc]; argc++)
2798 mkssert(wp[0] != NULL);
2800 if (strcmp(wp[0], "[") == 0) {
2801 if (strcmp(wp[--argc], "]") != 0) {
2802 bi_errorf("missing ]");
2803 return (T_ERR_EXIT);
2808 te.wp_end = wp + argc;
2811 * Attempt to conform to POSIX special cases. This is pretty
2812 * dumb code straight-forward from the 2008 spec, but unless
2813 * the old pdksh code doesn't live from so many assumptions.
2814 * It does, though, inline some calls to '(*te.funcname)()'.
2825 if (ptest_isa(&te, TM_NOT)) {
2829 if ((op = ptest_isa(&te, TM_UNOP))) {
2831 rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
2833 return ((invert & 1) ? rv : !rv);
2835 /* let the parser deal with anything else */
2840 /* use inside knowledge of ptest_getopnd inlined below */
2842 if ((op = ptest_isa(&te, TM_BINOP))) {
2843 /* test lhs op rhs */
2844 rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
2847 /* back up to lhs */
2849 if (ptest_isa(&te, TM_NOT)) {
2853 if (ptest_isa(&te, TM_OPAREN)) {
2855 /* skip operand, without evaluation */
2857 /* check for closing parenthesis */
2858 op = ptest_isa(&te, TM_CPAREN);
2859 /* back up to operand */
2861 /* if there was a closing paren, handle it */
2864 /* backing up is done before calling the parser */
2866 /* let the parser deal with it */
2869 if (ptest_isa(&te, TM_NOT)) {
2873 if (ptest_isa(&te, TM_OPAREN)) {
2875 /* skip two operands, without evaluation */
2878 /* check for closing parenthesis */
2879 op = ptest_isa(&te, TM_CPAREN);
2880 /* back up to first operand */
2882 /* if there was a closing paren, handle it */
2885 /* backing up is done before calling the parser */
2887 /* defer this to the parser */
2891 /* "The results are unspecified." */
2893 return (test_parse(&te));
2897 * Generic test routines.
2901 test_isop(Test_meta meta, const char *s)
2904 const struct t_op *tbl;
2906 tbl = meta == TM_UNOP ? u_ops : b_ops;
2909 for (; tbl->op_text[0]; tbl++)
2910 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
2911 return (tbl->op_num);
2917 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
2930 /* Binary operators */
2944 /* consistency check, but does not happen in practice */
2946 te->flags |= TEF_ERROR;
2951 /* for completeness of switch */
2964 return (*opnd1 != '\0');
2968 return (*opnd1 == '\0');
2972 if ((i = *opnd1) == '!' || i == '?')
2974 if ((k = option(opnd1)) == (size_t)-1)
2976 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
2980 /* LINTED use of access */
2981 return (access(opnd1, R_OK) == 0);
2985 /* LINTED use of access */
2986 return (access(opnd1, W_OK) == 0);
2990 return (ksh_access(opnd1, X_OK) == 0);
2996 return (stat(opnd1, &b1) == 0);
3000 return (stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
3004 return (stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
3008 return (stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
3012 return (stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
3016 return (stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
3020 #ifdef MKSH__NO_SYMLINK
3023 return (lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
3028 return (stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
3030 /* -H => HP context dependent files (directories) */
3037 * Append a + to filename and check to see if result is
3038 * a setuid directory. CDF stuff in general is hookey,
3039 * since it breaks for, e.g., the following sequence:
3040 * echo hi >foo+; mkdir foo; echo bye >foo/default;
3041 * chmod u+s foo (foo+ refers to the file with hi in it,
3042 * there is no way to get at the file with bye in it;
3043 * please correct me if I'm wrong about this).
3046 nv = shf_smprintf("%s+", opnd1);
3047 i = (stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
3057 return (stat(opnd1, &b1) == 0 &&
3058 (b1.st_mode & S_ISUID) == S_ISUID);
3062 return (stat(opnd1, &b1) == 0 &&
3063 (b1.st_mode & S_ISGID) == S_ISGID);
3068 return (stat(opnd1, &b1) == 0 &&
3069 (b1.st_mode & S_ISVTX) == S_ISVTX);
3076 return (stat(opnd1, &b1) == 0 && (off_t)b1.st_size > (off_t)0);
3080 if (opnd1 && !bi_getn(opnd1, &i)) {
3081 te->flags |= TEF_ERROR;
3084 i = isatty(opnd1 ? i : 0);
3089 return (stat(opnd1, &b1) == 0 && (uid_t)b1.st_uid == ksheuid);
3093 return (stat(opnd1, &b1) == 0 && (gid_t)b1.st_gid == getegid());
3101 if (te->flags & TEF_DBRACKET)
3102 return (gmatchx(opnd1, opnd2, false));
3103 return (strcmp(opnd1, opnd2) == 0);
3107 if (te->flags & TEF_DBRACKET)
3108 return (!gmatchx(opnd1, opnd2, false));
3109 return (strcmp(opnd1, opnd2) != 0);
3113 return (strcmp(opnd1, opnd2) < 0);
3117 return (strcmp(opnd1, opnd2) > 0);
3131 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
3132 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
3133 /* error already printed.. */
3134 te->flags |= TEF_ERROR;
3159 * ksh88/ksh93 succeed if file2 can't be stated
3160 * (subtly different from 'does not exist').
3162 return (stat(opnd1, &b1) == 0 &&
3163 (((s = stat(opnd2, &b2)) == 0 &&
3164 b1.st_mtime > b2.st_mtime) || s < 0));
3169 * ksh88/ksh93 succeed if file1 can't be stated
3170 * (subtly different from 'does not exist').
3172 return (stat(opnd2, &b2) == 0 &&
3173 (((s = stat(opnd1, &b1)) == 0 &&
3174 b1.st_mtime < b2.st_mtime) || s < 0));
3178 return (stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0 &&
3179 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
3181 /* all other cases */
3184 /* throw the error */
3187 (*te->error)(te, 0, "internal error: unknown op");
3192 test_parse(Test_env *te)
3196 rv = test_oexpr(te, 1);
3198 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3199 (*te->error)(te, 0, "unexpected operator/operand");
3201 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3205 test_oexpr(Test_env *te, bool do_eval)
3209 if ((rv = test_aexpr(te, do_eval)))
3211 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3212 return (test_oexpr(te, do_eval) || rv);
3217 test_aexpr(Test_env *te, bool do_eval)
3221 if (!(rv = test_nexpr(te, do_eval)))
3223 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3224 return (test_aexpr(te, do_eval) && rv);
3229 test_nexpr(Test_env *te, bool do_eval)
3231 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3232 return (!test_nexpr(te, do_eval));
3233 return (test_primary(te, do_eval));
3237 test_primary(Test_env *te, bool do_eval)
3239 const char *opnd1, *opnd2;
3243 if (te->flags & TEF_ERROR)
3245 if ((*te->isa)(te, TM_OPAREN)) {
3246 rv = test_oexpr(te, do_eval);
3247 if (te->flags & TEF_ERROR)
3249 if (!(*te->isa)(te, TM_CPAREN)) {
3250 (*te->error)(te, 0, "missing )");
3256 * Binary should have precedence over unary in this case
3257 * so that something like test \( -f = -f \) is accepted
3259 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3260 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3261 if ((op = (*te->isa)(te, TM_UNOP))) {
3262 /* unary expression */
3263 opnd1 = (*te->getopnd)(te, op, do_eval);
3265 (*te->error)(te, -1, "missing argument");
3269 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3272 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3274 (*te->error)(te, 0, "expression expected");
3277 if ((op = (*te->isa)(te, TM_BINOP))) {
3278 /* binary expression */
3279 opnd2 = (*te->getopnd)(te, op, do_eval);
3281 (*te->error)(te, -1, "missing second argument");
3285 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3287 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3291 * Plain test (test and [ .. ]) specific routines.
3295 * Test if the current token is a whatever. Accepts the current token if
3296 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3297 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3300 ptest_isa(Test_env *te, Test_meta meta)
3302 /* Order important - indexed by Test_meta values */
3303 static const char * const tokens[] = {
3304 "-o", "-a", "!", "(", ")"
3308 if (te->pos.wp >= te->wp_end)
3309 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3311 if (meta == TM_UNOP || meta == TM_BINOP)
3312 rv = test_isop(meta, *te->pos.wp);
3313 else if (meta == TM_END)
3316 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3317 TO_NONNULL : TO_NONOP;
3319 /* Accept the token? */
3327 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3329 if (te->pos.wp >= te->wp_end)
3330 return (op == TO_FILTT ? "1" : NULL);
3331 return (*te->pos.wp++);
3335 ptest_error(Test_env *te, int ofs, const char *msg)
3339 te->flags |= TEF_ERROR;
3340 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3341 bi_errorf("%s: %s", op, msg);
3343 bi_errorf("%s", msg);
3346 #ifndef MKSH_NO_LIMITS
3350 /* Magic to divine the 'm' and 'v' limits */
3353 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3354 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3355 #define ULIMIT_V_IS_AS
3356 #elif defined(RLIMIT_VMEM)
3357 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3358 #define ULIMIT_V_IS_AS
3360 #define ULIMIT_V_IS_VMEM
3366 #ifdef ULIMIT_V_IS_VMEM
3367 #define ULIMIT_M_IS_RSS
3368 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3369 #define ULIMIT_M_IS_VMEM
3371 #define ULIMIT_M_IS_RSS
3373 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3374 #undef ULIMIT_M_IS_RSS
3378 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3379 #define ULIMIT_V_IS_VMEM
3382 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3383 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3384 #define ULIMIT_M_IS_VMEM
3387 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3388 (RLIMIT_VMEM == RLIMIT_AS)
3389 #undef ULIMIT_M_IS_VMEM
3392 #if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
3393 # error nonsensical m ulimit
3396 #if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
3397 # error nonsensical v ulimit
3400 #define RLIMITS_DEFNS
3401 #include "rlimits.gen"
3403 static void print_ulimit(const struct limits *, int);
3404 static int set_ulimit(const struct limits *, const char *, int);
3406 static const struct limits * const rlimits[] = {
3407 #define RLIMITS_ITEMS
3408 #include "rlimits.gen"
3411 static const char rlimits_opts[] =
3412 #define RLIMITS_OPTCS
3413 #include "rlimits.gen"
3417 c_ulimit(const char **wp)
3420 int how = SOFT | HARD, optc, what = 'f';
3423 while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
3435 bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
3441 while (i < NELEM(rlimits)) {
3442 if (rlimits[i]->optchar == what)
3446 internal_warningf("ulimit: %c", what);
3449 if (wp[builtin_opt.optind]) {
3450 if (all || wp[builtin_opt.optind + 1]) {
3451 bi_errorf("too many arguments");
3454 return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
3457 print_ulimit(rlimits[i], how);
3458 else for (i = 0; i < NELEM(rlimits); ++i) {
3459 shprintf("%-20s ", rlimits[i]->name);
3460 print_ulimit(rlimits[i], how);
3466 set_ulimit(const struct limits *l, const char *v, int how)
3468 rlim_t val = (rlim_t)0;
3469 struct rlimit limit;
3471 if (strcmp(v, "unlimited") == 0)
3472 val = (rlim_t)RLIM_INFINITY;
3476 if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
3479 * Avoid problems caused by typos that evaluate misses due
3480 * to evaluating unset parameters to 0...
3481 * If this causes problems, will have to add parameter to
3482 * evaluate() to control if unset params are 0 or an error.
3484 if (!rval && !ksh_isdigit(v[0])) {
3485 bi_errorf("invalid %s limit: %s", l->name, v);
3488 val = (rlim_t)((rlim_t)rval * l->factor);
3491 if (getrlimit(l->resource, &limit) < 0) {
3493 bi_errorf("limit %s could not be read, contact the mksh developers: %s",
3494 l->name, cstrerror(errno));
3496 /* some can't be read */
3497 limit.rlim_cur = RLIM_INFINITY;
3498 limit.rlim_max = RLIM_INFINITY;
3501 limit.rlim_cur = val;
3503 limit.rlim_max = val;
3504 if (!setrlimit(l->resource, &limit))
3507 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3509 bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
3514 print_ulimit(const struct limits *l, int how)
3516 rlim_t val = (rlim_t)0;
3517 struct rlimit limit;
3519 if (getrlimit(l->resource, &limit)) {
3520 shf_puts("unknown\n", shl_stdout);
3524 val = limit.rlim_cur;
3525 else if (how & HARD)
3526 val = limit.rlim_max;
3527 if (val == (rlim_t)RLIM_INFINITY)
3528 shf_puts("unlimited\n", shl_stdout);
3530 shprintf("%lu\n", (unsigned long)(val / l->factor));
3535 c_rename(const char **wp)
3541 if (wp[0] && !strcmp(wp[0], "--"))
3542 /* skip "--" (options separator) */
3545 /* check for exactly two arguments */
3546 if (wp[0] == NULL /* first argument */ ||
3547 wp[1] == NULL /* second argument */ ||
3548 wp[2] != NULL /* no further args please */)
3550 else if ((rv = rename(wp[0], wp[1])) != 0) {
3552 bi_errorf("%s: %s", "failed", cstrerror(rv));
3559 c_realpath(const char **wp)
3566 if (wp[0] && !strcmp(wp[0], "--"))
3567 /* skip "--" (options separator) */
3570 /* check for exactly one argument */
3571 if (wp[0] == NULL || wp[1] != NULL)
3573 else if ((buf = do_realpath(wp[0])) == NULL) {
3575 bi_errorf("%s: %s", wp[0], cstrerror(rv));
3576 if ((unsigned int)rv > 255)
3579 shprintf("%s\n", buf);
3588 c_cat(const char **wp)
3590 int fd = STDIN_FILENO, rv, eno;
3592 const char *fn = "<stdin>";
3594 #define MKSH_CAT_BUFSIZ 4096
3596 /* parse options: POSIX demands we support "-u" as no-op */
3597 while ((rv = ksh_getopt(wp, &builtin_opt, "u")) != -1) {
3600 /* we already operate unbuffered */
3607 wp += builtin_opt.optind;
3610 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3611 bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
3618 if (fn[0] == '-' && fn[1] == '\0')
3620 else if ((fd = open(fn, O_RDONLY | O_BINARY)) < 0) {
3622 bi_errorf("%s: %s", fn, cstrerror(eno));
3627 while (/* CONSTCOND */ 1) {
3628 n = blocking_read(fd, (cp = buf), MKSH_CAT_BUFSIZ);
3630 /* give the user a chance to ^C out */
3634 /* interrupted, try again */
3637 /* an error occured during reading */
3638 bi_errorf("%s: %s", fn, cstrerror(eno));
3642 /* end of file reached */
3645 w = write(STDOUT_FILENO, cp, n);
3648 /* interrupted, try again */
3650 /* an error occured during writing */
3652 bi_errorf("%s: %s", "<stdout>",
3655 if (fd != STDIN_FILENO)
3663 if (fd != STDIN_FILENO)
3674 c_sleep(const char **wp)
3681 if (wp[0] && !strcmp(wp[0], "--"))
3682 /* skip "--" (options separator) */
3685 if (!wp[0] || wp[1])
3687 else if (parse_usec(wp[0], &tv))
3688 bi_errorf("%s: %s '%s'", Tsynerr, cstrerror(errno), wp[0]);
3690 #ifndef MKSH_NOPROSPECTOFWORK
3691 sigset_t omask, bmask;
3693 /* block a number of signals from interrupting us, though */
3694 (void)sigemptyset(&bmask);
3695 (void)sigaddset(&bmask, SIGPIPE);
3696 (void)sigaddset(&bmask, SIGCHLD);
3698 (void)sigaddset(&bmask, SIGWINCH);
3701 (void)sigaddset(&bmask, SIGINFO);
3704 (void)sigaddset(&bmask, SIGUSR1);
3707 (void)sigaddset(&bmask, SIGUSR2);
3709 sigprocmask(SIG_BLOCK, &bmask, &omask);
3711 if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3713 * strictly speaking only for SIGALRM, but the
3714 * execution may be interrupted by other signals
3718 bi_errorf("%s: %s", Tselect, cstrerror(errno));
3719 #ifndef MKSH_NOPROSPECTOFWORK
3720 /* this will re-schedule signal delivery */
3721 sigprocmask(SIG_SETMASK, &omask, NULL);
3728 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
3730 c_suspend(const char **wp)
3732 if (wp[1] != NULL) {
3733 bi_errorf("too many arguments");
3737 /* Can't suspend an orphaned process group. */
3738 if (getpgid(kshppid) == getpgid(0) ||
3739 getsid(kshppid) != getsid(0)) {
3740 bi_errorf("can't suspend a login shell");