1 /* $OpenBSD: c_ksh.c,v 1.33 2009/02/07 14:03:24 kili Exp $ */
2 /* $OpenBSD: c_sh.c,v 1.41 2010/03/27 09:10:01 jmc Exp $ */
3 /* $OpenBSD: c_test.c,v 1.18 2009/03/01 20:11:06 otto Exp $ */
4 /* $OpenBSD: c_ulimit.c,v 1.17 2008/03/21 12:51:19 millert Exp $ */
7 * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
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.197 2011/09/07 15:24:15 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
64 static int c_android_lsmod(const char **);
68 c_true(const char **wp MKSH_A_UNUSED)
74 c_false(const char **wp MKSH_A_UNUSED)
80 * A leading = means assignments before command are kept;
81 * a leading * means a POSIX special builtin;
82 * a leading + means a POSIX regular builtin
83 * (* and + should not be combined).
85 const struct builtin mkshbuiltins[] = {
89 {"*=break", c_brkcont},
90 {Tgbuiltin, c_builtin},
91 {"*=continue", c_brkcont},
94 {"*=exit", c_exitreturn},
96 {"*=return", c_exitreturn},
105 {"ulimit", c_ulimit},
107 {"*=unset", c_unset},
108 /* no =: AT&T manual wrong */
111 /* dash compatibility hack */
113 {"+command", c_command},
115 {"*=export", c_typeset},
117 {"+getopts", c_getopts},
118 {"=global", c_typeset},
123 #ifdef MKSH_PRINTF_BUILTIN
124 {"printf", c_printf},
127 {"*=readonly", c_typeset},
128 {T_typeset, c_typeset},
129 {Tpunalias, c_unalias},
130 {"whence", c_whence},
131 #ifndef MKSH_UNEMPLOYED
140 {"realpath", c_realpath},
141 {"rename", c_rename},
146 /* alias to "true" for historical reasons */
147 {"domainname", c_true},
150 {"lsmod", c_android_lsmod},
152 {NULL, (int (*)(const char **))NULL}
160 static const struct t_op {
190 static const struct t_op b_ops[] = {
208 static int test_oexpr(Test_env *, bool);
209 static int test_aexpr(Test_env *, bool);
210 static int test_nexpr(Test_env *, bool);
211 static int test_primary(Test_env *, bool);
212 static Test_op ptest_isa(Test_env *, Test_meta);
213 static const char *ptest_getopnd(Test_env *, Test_op, bool);
214 static void ptest_error(Test_env *, int, const char *);
215 static char *kill_fmt_entry(char *, size_t, int, const void *);
216 static void p_time(struct shf *, bool, long, int, int,
217 const char *, const char *)
218 MKSH_A_NONNULL((__nonnull__ (6, 7)));
221 c_pwd(const char **wp)
224 bool physical = tobool(Flag(FPHYSICAL));
225 char *p, *allocd = NULL;
227 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
238 wp += builtin_opt.optind;
241 bi_errorf("too many arguments");
244 p = current_wd[0] ? (physical ? allocd = do_realpath(current_wd) :
246 /* LINTED use of access */
247 if (p && access(p, R_OK) < 0)
249 if (!p && !(p = allocd = ksh_get_wd())) {
250 bi_errorf("%s: %s", "can't determine current directory",
255 afree(allocd, ATEMP);
259 static const char *s_ptr;
260 static int s_get(void);
261 static void s_put(int);
264 c_print(const char **wp)
266 #define PO_NL BIT(0) /* print newline */
267 #define PO_EXPAND BIT(1) /* expand backslash sequences */
268 #define PO_PMINUSMINUS BIT(2) /* print a -- argument */
269 #define PO_HIST BIT(3) /* print to history instead of stdout */
270 #define PO_COPROC BIT(4) /* printing to coprocess: block SIGPIPE */
272 int flags = PO_EXPAND|PO_NL;
273 const char *s, *emsg;
277 if (wp[0][0] == 'e') {
280 if (Flag(FPOSIX) || Flag(FSH) || Flag(FAS_BUILTIN)) {
281 /* Debian Policy 10.4 compliant "echo" builtin */
282 if (*wp && !strcmp(*wp, "-n")) {
283 /* we recognise "-n" only as the first arg */
287 /* otherwise, we print everything as-is */
293 * a compromise between sysV and BSD echo commands:
294 * escape sequences are enabled by default, and -n,
295 * -e and -E are recognised if they appear in argu-
296 * ments with no illegal options (ie, echo -nq will
298 * Different from sysV echo since options are reco-
299 * gnised, different from BSD echo since escape se-
300 * quences are enabled by default.
303 while ((s = *wp) && *s == '-' && s[1]) {
310 nflags &= ~PO_EXPAND;
313 * bad option: don't use
314 * nflags, print argument
326 const char *opts = "Rnprsu,";
328 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1)
331 /* fake BSD echo command */
332 flags |= PO_PMINUSMINUS;
343 if ((fd = coproc_getfd(W_OK, &emsg)) < 0) {
344 bi_errorf("%s: %s", "-p", emsg);
355 if (!*(s = builtin_opt.optarg))
357 else if ((fd = check_fd(s, W_OK, &emsg)) < 0) {
358 bi_errorf("%s: %s: %s", "-u", s, emsg);
366 if (!(builtin_opt.info & GI_MINUSMINUS)) {
367 /* treat a lone - like -- */
368 if (wp[builtin_opt.optind] &&
369 ksh_isdash(wp[builtin_opt.optind]))
370 builtin_opt.optind++;
371 } else if (flags & PO_PMINUSMINUS)
372 builtin_opt.optind--;
373 wp += builtin_opt.optind;
376 Xinit(xs, xp, 128, ATEMP);
378 while (*wp != NULL) {
380 while ((c = *s++) != '\0') {
382 if ((flags & PO_EXPAND) && c == '\\') {
384 c = unbksl(false, s_get, s_put);
387 /* rejected by generic function */
388 switch ((c = *s++)) {
391 /* AT&T brain damage */
400 } else if ((unsigned int)c > 0xFF) {
401 /* generic function returned Unicode */
404 ts[utf_wctomb(ts, c - 0x100)] = 0;
405 for (c = 0; ts[c]; ++c)
418 if (flags & PO_HIST) {
420 histsave(&source->line, Xstring(xs, xp), true, false);
423 int len = Xlength(xs, xp);
427 * Ensure we aren't killed by a SIGPIPE while writing to
428 * a coprocess. AT&T ksh doesn't seem to do this (seems
429 * to just check that the co-process is alive which is
432 if (coproc.write >= 0 && coproc.write == fd) {
434 opipe = block_pipe();
436 for (s = Xstring(xs, xp); len > 0; ) {
437 if ((c = write(fd, s, len)) < 0) {
438 if (flags & PO_COPROC)
440 if (errno == EINTR) {
441 /* allow user to ^C out */
443 if (flags & PO_COPROC)
444 opipe = block_pipe();
452 if (flags & PO_COPROC)
466 s_put(int c MKSH_A_UNUSED)
472 c_whence(const char **wp)
476 bool pflag = false, vflag = false, Vflag = false;
477 int rv = 0, optc, fcflags;
478 bool iam_whence = wp[0][0] == 'w';
479 const char *opts = iam_whence ? "pv" : "pvV";
481 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1)
495 wp += builtin_opt.optind;
497 fcflags = FC_BI | FC_PATH | FC_FUNC;
499 /* Note that -p on its own is deal with in comexec() */
501 fcflags |= FC_DEFPATH;
503 * Convert command options to whence options - note that
504 * command -pV uses a different path search than whence -v
505 * or whence -pv. This should be considered a feature.
510 fcflags &= ~(FC_BI | FC_FUNC);
512 while ((vflag || rv == 0) && (id = *wp++) != NULL) {
516 if ((iam_whence || vflag) && !pflag)
517 tp = ktsearch(&keywords, id, h = hash(id));
519 tp = ktsearch(&aliases, id, h ? h : hash(id));
520 if (tp && !(tp->flag & ISSET))
524 tp = findcom(id, fcflags);
525 if (vflag || (tp->type != CALIAS && tp->type != CEXEC &&
526 tp->type != CTALIAS))
527 shf_puts(id, shl_stdout);
534 shf_puts(" is a", shl_stdout);
541 shf_puts(" reserved word", shl_stdout);
545 shprintf("n %s%s for ",
546 (tp->flag & EXPORT) ? "exported " : null,
548 if (!iam_whence && !vflag)
549 shprintf("%s %s=", Talias, id);
550 print_value_quoted(tp->val.s);
554 if (tp->flag & EXPORT)
555 shf_puts("n exported", shl_stdout);
556 if (tp->flag & TRACE)
557 shf_puts(" traced", shl_stdout);
558 if (!(tp->flag & ISSET)) {
559 shf_puts(" undefined", shl_stdout);
561 shprintf(" (autoload from %s)",
564 shf_puts(T_function, shl_stdout);
570 (tp->flag & SPEC_BI) ? " special" : null,
575 if (tp->flag & ISSET) {
577 shf_puts(" is ", shl_stdout);
578 if (tp->type == CTALIAS)
579 shprintf("a tracked %s%s for ",
580 (tp->flag & EXPORT) ?
584 shf_puts(tp->val.s, shl_stdout);
587 shprintf(" %s\n", "not found");
592 shprintf("%s is *GOK*", id);
596 shf_putc('\n', shl_stdout);
601 /* Deal with command -vV - command -p dealt with in comexec() */
603 c_command(const char **wp)
606 * Let c_whence do the work. Note that c_command() must be
607 * a distinct function from c_whence() (tested in comexec()).
609 return (c_whence(wp));
612 /* typeset, global, export, and readonly */
614 c_typeset(const char **wp)
618 uint32_t fset = 0, fclr = 0, flag;
619 int thing = 0, field, base, optc;
621 const char *fieldstr, *basestr;
622 bool localv = false, func = false, pflag = false, istset = true;
640 /* called with 'typeset -' */
649 /* see comment below regarding possible opions */
650 opts = istset ? "L#R#UZ#afi#lnprtux" : "p";
652 fieldstr = basestr = NULL;
653 builtin_opt.flags |= GF_PLUSOPT;
655 * AT&T ksh seems to have 0-9 as options which are multiplied
656 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
657 * sets right justify in a field of 12). This allows options
658 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
659 * does not allow the number to be specified as a separate argument
660 * Here, the number must follow the RLZi option, but is optional
661 * (see the # kludge in ksh_getopt()).
663 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
668 fieldstr = builtin_opt.optarg;
672 fieldstr = builtin_opt.optarg;
676 * AT&T ksh uses u, but this conflicts with
677 * upper/lower case. If this option is changed,
678 * need to change the -U below as well
684 fieldstr = builtin_opt.optarg;
688 * this is supposed to set (-a) or unset (+a) the
689 * indexed array attribute; it does nothing on an
690 * existing regular string or indexed array though
698 basestr = builtin_opt.optarg;
704 set_refflag = (builtin_opt.info & GI_PLUS) ?
705 SRF_DISABLE : SRF_ENABLE;
707 /* export, readonly: POSIX -p flag */
709 /* typeset: show values as well */
721 /* upper case / autoload */
730 if (builtin_opt.info & GI_PLUS) {
742 if (fieldstr && !bi_getn(fieldstr, &field))
745 if (basestr && !bi_getn(basestr, &base))
748 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
749 (wp[builtin_opt.optind][0] == '-' ||
750 wp[builtin_opt.optind][0] == '+') &&
751 wp[builtin_opt.optind][1] == '\0') {
752 thing = wp[builtin_opt.optind][0];
753 builtin_opt.optind++;
756 if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
757 set_refflag != SRF_NOP)) {
758 bi_errorf("only -t, -u and -x options may be used with -f");
759 set_refflag = SRF_NOP;
762 if (wp[builtin_opt.optind]) {
764 * Take care of exclusions.
765 * At this point, flags in fset are cleared in fclr and vice
766 * versa. This property should be preserved.
769 /* LCASEV has priority over UCASEV_AL */
772 /* LJUST has priority over RJUST */
774 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
780 * Setting these attributes clears the others, unless they
781 * are also set in this command
783 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
784 INTEGER | INT_U | INT_L)) || set_refflag != SRF_NOP)
785 fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
786 LCASEV | INTEGER | INT_U | INT_L);
789 /* set variables and attributes */
790 if (wp[builtin_opt.optind]) {
796 for (i = builtin_opt.optind; wp[i]; i++) {
798 f = findfunc(wp[i], hash(wp[i]),
799 tobool(fset & UCASEV_AL));
801 /* AT&T ksh does ++rv: bogus */
809 fpFUNCTf(shl_stdout, 0,
810 tobool(f->flag & FKSH),
812 shf_putc('\n', shl_stdout);
814 } else if (!typeset(wp[i], fset, fclr, field, base)) {
815 bi_errorf("%s: %s", wp[i], "not identifier");
816 set_refflag = SRF_NOP;
820 set_refflag = SRF_NOP;
824 /* list variables and attributes */
826 /* no difference at this point.. */
829 for (l = e->loc; l; l = l->next) {
830 for (p = ktsort(&l->funs); (vp = *p++); ) {
831 if (flag && (vp->flag & flag) == 0)
834 fpFUNCTf(shl_stdout, 0,
835 tobool(vp->flag & FKSH),
836 vp->name, vp->val.t);
838 shf_puts(vp->name, shl_stdout);
839 shf_putc('\n', shl_stdout);
843 for (l = e->loc; l; l = l->next) {
844 for (p = ktsort(&l->vars); (vp = *p++); ) {
846 bool any_set = false;
848 * See if the parameter is set (for arrays, if any
851 for (tvp = vp; tvp; tvp = tvp->u.array)
852 if (tvp->flag & ISSET) {
858 * Check attributes - note that all array elements
859 * have (should have?) the same attributes, so checking
860 * the first is sufficient.
862 * Report an unset param only if the user has
863 * explicitly given it some attribute (like export);
864 * otherwise, after "echo $FOO", we would report FOO...
866 if (!any_set && !(vp->flag & USERATTRIB))
868 if (flag && (vp->flag & flag) == 0)
870 for (; vp; vp = vp->u.array) {
872 * Ignore array elements that aren't
873 * set unless there are no set elements,
874 * in which case the first is reported on
876 if ((vp->flag&ARRAY) && any_set &&
880 if (thing == 0 && flag == 0) {
882 * AT&T ksh prints things
883 * like export, integer,
884 * leftadj, zerofill, etc.,
885 * but POSIX says must
886 * be suitable for re-entry...
888 shf_puts("typeset ", shl_stdout);
889 if (((vp->flag&(ARRAY|ASSOC))==ASSOC))
890 shprintf("%s ", "-n");
891 if ((vp->flag&INTEGER))
892 shprintf("%s ", "-i");
893 if ((vp->flag&EXPORT))
894 shprintf("%s ", "-x");
895 if ((vp->flag&RDONLY))
896 shprintf("%s ", "-r");
897 if ((vp->flag&TRACE))
898 shprintf("%s ", "-t");
899 if ((vp->flag&LJUST))
900 shprintf("-L%d ", vp->u2.field);
901 if ((vp->flag&RJUST))
902 shprintf("-R%d ", vp->u2.field);
903 if ((vp->flag&ZEROFIL))
904 shprintf("%s ", "-Z");
905 if ((vp->flag&LCASEV))
906 shprintf("%s ", "-l");
907 if ((vp->flag&UCASEV_AL))
908 shprintf("%s ", "-u");
909 if ((vp->flag&INT_U))
910 shprintf("%s ", "-U");
911 shf_puts(vp->name, shl_stdout);
913 char *s = str_val(vp);
915 shf_putc('=', shl_stdout);
917 * AT&T ksh can't have
918 * justified integers...
921 (INTEGER|LJUST|RJUST)) ==
923 shf_puts(s, shl_stdout);
925 print_value_quoted(s);
927 shf_putc('\n', shl_stdout);
928 if (vp->flag & ARRAY)
938 if ((vp->flag&ARRAY) && any_set)
943 shf_puts(vp->name, shl_stdout);
944 if (thing == '-' && (vp->flag&ISSET)) {
945 char *s = str_val(vp);
947 shf_putc('=', shl_stdout);
949 * AT&T ksh can't have
950 * justified integers...
953 (INTEGER|LJUST|RJUST)) ==
955 shf_puts(s, shl_stdout);
957 print_value_quoted(s);
959 shf_putc('\n', shl_stdout);
962 * Only report first 'element' of an array with
975 c_alias(const char **wp)
977 struct table *t = &aliases;
978 int rv = 0, prefix = 0;
979 bool rflag = false, tflag, Uflag = false, pflag = false;
983 builtin_opt.flags |= GF_PLUSOPT;
984 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
985 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
989 t = NULL; /* fix "alias -dt" */
1005 * kludge for tracked alias initialization
1006 * (don't do a path search, just make an entry)
1021 wp += builtin_opt.optind;
1023 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
1024 (wp[0][0] == '-' || wp[0][0] == '+') && wp[0][1] == '\0') {
1029 tflag = t == &taliases;
1031 /* "hash -r" means reset all the tracked aliases.. */
1033 static const char *args[] = {
1034 Tunalias, "-ta", NULL
1037 if (!tflag || *wp) {
1038 shprintf("%s: -r flag can only be used with -t"
1039 " and without arguments\n", Talias);
1042 ksh_getopt_reset(&builtin_opt, GF_ERROR);
1043 return (c_unalias(args));
1047 struct tbl *ap, **p;
1049 for (p = ktsort(t); (ap = *p++) != NULL; )
1050 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
1052 shprintf("%s ", Talias);
1053 shf_puts(ap->name, shl_stdout);
1054 if (prefix != '+') {
1055 shf_putc('=', shl_stdout);
1056 print_value_quoted(ap->val.s);
1058 shf_putc('\n', shl_stdout);
1062 for (; *wp != NULL; wp++) {
1063 const char *alias = *wp, *val, *newval;
1064 char *xalias = NULL;
1068 if ((val = cstrchr(alias, '='))) {
1069 strndupx(xalias, alias, val++ - alias, ATEMP);
1073 if (val == NULL && !tflag && !xflag) {
1074 ap = ktsearch(t, alias, h);
1075 if (ap != NULL && (ap->flag&ISSET)) {
1077 shprintf("%s ", Talias);
1078 shf_puts(ap->name, shl_stdout);
1079 if (prefix != '+') {
1080 shf_putc('=', shl_stdout);
1081 print_value_quoted(ap->val.s);
1083 shf_putc('\n', shl_stdout);
1085 shprintf("%s %s %s\n", alias, Talias,
1091 ap = ktenter(t, alias, h);
1092 ap->type = tflag ? CTALIAS : CALIAS;
1093 /* Are we setting the value or just some flags? */
1094 if ((val && !tflag) || (!val && tflag && !Uflag)) {
1095 if (ap->flag&ALLOC) {
1096 ap->flag &= ~(ALLOC|ISSET);
1097 afree(ap->val.s, APERM);
1099 /* ignore values for -t (AT&T ksh does this) */
1101 search_path(alias, path, X_OK, NULL) :
1104 strdupx(ap->val.s, newval, APERM);
1105 ap->flag |= ALLOC|ISSET;
1109 ap->flag |= DEFINED;
1114 afree(xalias, ATEMP);
1121 c_unalias(const char **wp)
1123 struct table *t = &aliases;
1128 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
1135 /* fix "unalias -dt" */
1151 wp += builtin_opt.optind;
1153 for (; *wp != NULL; wp++) {
1154 ap = ktsearch(t, *wp, hash(*wp));
1160 if (ap->flag&ALLOC) {
1161 ap->flag &= ~(ALLOC|ISSET);
1162 afree(ap->val.s, APERM);
1164 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1170 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
1171 if (ap->flag&ALLOC) {
1172 ap->flag &= ~(ALLOC|ISSET);
1173 afree(ap->val.s, APERM);
1175 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1183 c_let(const char **wp)
1189 /* AT&T ksh does this */
1190 bi_errorf("no arguments");
1192 for (wp++; *wp; wp++)
1193 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
1194 /* distinguish error from zero result */
1203 c_jobs(const char **wp)
1205 int optc, flag = 0, nflag = 0, rv = 0;
1207 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1219 /* debugging: print zombies */
1225 wp += builtin_opt.optind;
1227 if (j_jobs(NULL, flag, nflag))
1231 if (j_jobs(*wp, flag, nflag))
1237 #ifndef MKSH_UNEMPLOYED
1239 c_fgbg(const char **wp)
1241 bool bg = strcmp(*wp, "bg") == 0;
1244 if (!Flag(FMONITOR)) {
1245 bi_errorf("job control not enabled");
1248 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1250 wp += builtin_opt.optind;
1253 rv = j_resume(*wp, bg);
1255 rv = j_resume("%%", bg);
1256 return (bg ? 0 : rv);
1260 /* format a single kill item */
1262 kill_fmt_entry(char *buf, size_t buflen, int i, const void *arg)
1264 const struct kill_info *ki = (const struct kill_info *)arg;
1267 shf_snprintf(buf, buflen, "%*d %*s %s",
1269 ki->name_width, sigtraps[i].name,
1275 c_kill(const char **wp)
1282 /* assume old style options if -digits or -UPPERCASE */
1283 if ((p = wp[1]) && *p == '-' && (ksh_isdigit(p[1]) ||
1284 ksh_isupper(p[1]))) {
1285 if (!(t = gettrap(p + 1, true))) {
1286 bi_errorf("bad signal '%s'", p + 1);
1289 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1293 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1299 if (!(t = gettrap(builtin_opt.optarg, true))) {
1300 bi_errorf("bad signal '%s'",
1301 builtin_opt.optarg);
1308 i = builtin_opt.optind;
1310 if ((lflag && t) || (!wp[i] && !lflag)) {
1312 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1313 " { job | pid | pgrp } ...\n"
1314 "\tkill -l [exit_status ...]\n", shl_out);
1322 for (; wp[i]; i++) {
1323 if (!bi_getn(wp[i], &n))
1325 if (n > 128 && n < 128 + NSIG)
1327 if (n > 0 && n < NSIG)
1328 shprintf("%s\n", sigtraps[n].name);
1330 shprintf("%d\n", n);
1333 ssize_t w, mess_cols, mess_octs;
1335 struct kill_info ki;
1337 for (j = NSIG, ki.num_width = 1; j >= 10; j /= 10)
1339 ki.name_width = mess_cols = mess_octs = 0;
1340 for (j = 0; j < NSIG; j++) {
1341 w = strlen(sigtraps[j].name);
1342 if (w > ki.name_width)
1344 w = strlen(sigtraps[j].mess);
1347 w = utf_mbswidth(sigtraps[j].mess);
1352 print_columns(shl_stdout, NSIG - 1,
1353 kill_fmt_entry, (void *)&ki,
1354 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1355 ki.num_width + 1 + ki.name_width + 1 + mess_cols,
1361 sig = t ? t->signal : SIGTERM;
1362 for (; (p = wp[i]); i++) {
1366 } else if (!getn(p, &n)) {
1367 bi_errorf("%s: %s", p,
1368 "arguments must be jobs or process IDs");
1371 if (mksh_kill(n, sig) < 0) {
1372 bi_errorf("%s: %s", p, strerror(errno));
1381 getopts_reset(int val)
1384 ksh_getopt_reset(&user_opt, GF_NONAME | GF_PLUSOPT);
1385 user_opt.optind = user_opt.uoptind = val;
1390 c_getopts(const char **wp)
1393 const char *opts, *var;
1395 struct tbl *vq, *voptarg;
1397 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1399 wp += builtin_opt.optind;
1403 bi_errorf("missing %s argument", "options");
1409 bi_errorf("missing %s argument", "name");
1412 if (!*var || *skip_varname(var, true)) {
1413 bi_errorf("%s: %s", var, "is not an identifier");
1417 if (e->loc->next == NULL) {
1418 internal_warningf("%s: %s", "c_getopts", "no argv");
1421 /* Which arguments are we parsing... */
1423 wp = e->loc->next->argv;
1425 *--wp = e->loc->next->argv[0];
1427 /* Check that our saved state won't cause a core dump... */
1428 for (argc = 0; wp[argc]; argc++)
1430 if (user_opt.optind > argc ||
1432 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1433 bi_errorf("arguments changed since last call");
1437 user_opt.optarg = NULL;
1438 optc = ksh_getopt(wp, &user_opt, opts);
1440 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1446 * POSIX says var is set to ? at end-of-options, AT&T ksh
1447 * sets it to null - we go with POSIX...
1449 buf[0] = optc < 0 ? '?' : optc;
1453 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1454 user_opt.uoptind = user_opt.optind;
1456 voptarg = global("OPTARG");
1457 /* AT&T ksh clears ro and int */
1458 voptarg->flag &= ~RDONLY;
1459 /* Paranoia: ensure no bizarre results. */
1460 if (voptarg->flag & INTEGER)
1461 typeset("OPTARG", 0, INTEGER, 0, 0);
1462 if (user_opt.optarg == NULL)
1465 /* This can't fail (have cleared readonly/integer) */
1466 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1471 /* Error message already printed (integer, readonly) */
1472 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1475 typeset(var, EXPORT, 0, 0, 0);
1477 return (optc < 0 ? 1 : rv);
1481 c_bind(const char **wp)
1491 while ((optc = ksh_getopt(wp, &builtin_opt,
1510 wp += builtin_opt.optind;
1514 rv = x_bind(NULL, NULL,
1520 for (; *wp != NULL; wp++) {
1521 if ((cp = cstrchr(*wp, '=')) == NULL)
1524 strdupx(up, *wp, ATEMP);
1525 up[cp++ - *wp] = '\0';
1527 if (x_bind(up ? up : *wp, cp,
1540 c_shift(const char **wp)
1542 struct block *l = e->loc;
1547 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1549 arg = wp[builtin_opt.optind];
1552 evaluate(arg, &val, KSH_UNWIND_ERROR, false);
1557 bi_errorf("%s: %s", arg, "bad number");
1561 bi_errorf("nothing to shift");
1564 l->argv[n] = l->argv[0];
1571 c_umask(const char **wp)
1575 bool symbolic = false;
1578 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1586 cp = wp[builtin_opt.optind];
1588 old_umask = umask((mode_t)0);
1594 old_umask = ~old_umask;
1596 for (i = 0; i < 3; i++) {
1599 for (j = 0; j < 3; j++)
1600 if (old_umask & (1 << (8 - (3*i + j))))
1605 shprintf("%s\n", buf);
1607 shprintf("%#3.3o\n", (unsigned int)old_umask);
1611 if (ksh_isdigit(*cp)) {
1612 for (new_umask = 0; *cp >= '0' && *cp <= '7'; cp++)
1613 new_umask = new_umask * 8 + (*cp - '0');
1615 bi_errorf("bad number");
1619 /* symbolic format */
1620 int positions, new_val;
1623 old_umask = umask((mode_t)0);
1624 /* in case of error */
1626 old_umask = ~old_umask;
1627 new_umask = old_umask;
1630 while (*cp && vstrchr("augo", *cp))
1648 if (!vstrchr("=+-", op = *cp))
1652 while (*cp && vstrchr("rwxugoXs", *cp))
1654 case 'r': new_val |= 04; break;
1655 case 'w': new_val |= 02; break;
1656 case 'x': new_val |= 01; break;
1658 new_val |= old_umask >> 6;
1661 new_val |= old_umask >> 3;
1664 new_val |= old_umask >> 0;
1667 if (old_umask & 0111)
1674 new_val = (new_val & 07) * positions;
1677 new_umask &= ~new_val;
1680 new_umask = new_val |
1681 (new_umask & ~(positions * 07));
1684 new_umask |= new_val;
1689 } else if (!vstrchr("=+-", *cp))
1693 bi_errorf("bad mask");
1696 new_umask = ~new_umask;
1704 c_dot(const char **wp)
1706 const char *file, *cp, **argv;
1707 int argc, i, errcode;
1709 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1712 if ((cp = wp[builtin_opt.optind]) == NULL) {
1713 bi_errorf("missing argument");
1716 if ((file = search_path(cp, path, R_OK, &errcode)) == NULL) {
1717 bi_errorf("%s: %s", cp, strerror(errcode));
1721 /* Set positional parameters? */
1722 if (wp[builtin_opt.optind + 1]) {
1723 argv = wp + builtin_opt.optind;
1725 argv[0] = e->loc->argv[0];
1726 for (argc = 0; argv[argc + 1]; argc++)
1732 if ((i = include(file, argc, argv, 0)) < 0) {
1733 /* should not happen */
1734 bi_errorf("%s: %s", cp, strerror(errno));
1741 c_wait(const char **wp)
1745 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1747 wp += builtin_opt.optind;
1749 while (waitfor(NULL, &sig) >= 0)
1754 rv = waitfor(*wp, &sig);
1756 /* magic exit code: bad job-id */
1757 rv = sig ? sig : 127;
1763 c_read(const char **wp)
1765 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1766 static char REPLY[] = "REPLY";
1767 int c, fd = 0, rv = 0, lastparm = 0;
1768 bool savehist = false, intoarray = false, aschars = false;
1769 bool rawmode = false, expanding = false;
1770 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1772 size_t bytesleft = 128, bytesread;
1773 struct tbl *vp /* FU gcc */ = NULL, *vq;
1774 char *cp, *allocd = NULL, *xp;
1777 ptrdiff_t xsave = 0;
1778 struct termios tios;
1779 bool restore_tios = false;
1781 bool hastimeout = false;
1782 struct timeval tv, tvlim;
1783 #define c_read_opts "Aad:N:n:prst:u,"
1785 #define c_read_opts "Aad:N:n:prsu,"
1788 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1797 delim = builtin_opt.optarg[0];
1801 readmode = c == 'N' ? BYTES : UPTO;
1802 if (!bi_getn(builtin_opt.optarg, &c))
1808 bytesleft = (unsigned int)c;
1811 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1812 bi_errorf("%s: %s", "-p", ccp);
1824 if (parse_usec(builtin_opt.optarg, &tv)) {
1825 bi_errorf("%s: %s '%s'", Tsynerr, strerror(errno),
1826 builtin_opt.optarg);
1833 if (!builtin_opt.optarg[0])
1835 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1836 bi_errorf("%s: %s: %s", "-u", builtin_opt.optarg, ccp);
1843 wp += builtin_opt.optind;
1847 if (intoarray && wp[1] != NULL) {
1848 bi_errorf("too many arguments");
1852 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1853 strdupx(allocd, *wp, ATEMP);
1854 allocd[ccp - *wp] = '\0';
1858 * AT&T ksh says it prints prompt on fd if it's open
1859 * for writing and is a tty, but it doesn't do it
1860 * (it also doesn't check the interactive flag,
1861 * as is indicated in the Korn Shell book).
1863 shf_puts(ccp + 1, shl_out);
1868 Xinit(xs, xp, bytesleft, ATEMP);
1870 if (readmode == LINES)
1872 else if (isatty(fd)) {
1873 x_mkraw(fd, &tios, true);
1874 restore_tios = true;
1879 gettimeofday(&tvlim, NULL);
1880 timeradd(&tvlim, &tv, &tvlim);
1891 gettimeofday(&tv, NULL);
1892 timersub(&tvlim, &tv, &tv);
1893 if (tv.tv_sec < 0) {
1894 /* timeout expired globally */
1899 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
1903 /* timeout expired for this call */
1907 bi_errorf("%s: %s", Tselect, strerror(errno));
1914 bytesread = blocking_read(fd, xp, bytesleft);
1915 if (bytesread == (size_t)-1) {
1917 if (errno == EINTR && fatal_trap_check()) {
1919 * Was the offending signal one that would
1920 * normally kill a process? If so, pretend
1921 * the read was killed.
1926 /* just ignore the signal */
1927 goto c_read_readloop;
1932 if (bytesread == 0) {
1933 /* end of file reached */
1935 goto c_read_readdone;
1938 XcheckN(xs, xp, bytesleft);
1943 /* end of file reached */
1946 goto c_read_readdone;
1949 if (bytesread == 0) {
1950 /* end of file reached */
1952 xp = Xstring(xs, xp);
1953 goto c_read_readdone;
1956 if ((bytesleft -= bytesread) == 0)
1957 goto c_read_readdone;
1960 if (bytesread == 0) {
1961 /* end of file reached */
1963 goto c_read_readdone;
1965 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
1966 /* skip any read NULs unless delimiter */
1972 if (Flag(FTALKING_I) && isatty(fd)) {
1974 * set prompt in case this is
1975 * called from .profile or $ENV
1977 set_prompt(PS2, NULL);
1980 /* drop the backslash */
1982 /* and the delimiter */
1985 } else if (c == delim) {
1986 goto c_read_readdone;
1987 } else if (!rawmode && c == '\\') {
1994 goto c_read_readloop;
1997 bytesread = Xlength(xs, xp);
2001 * state: we finished reading the input and NUL terminated it
2002 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
2003 * rv = 1 if EOF, 0 otherwise (errors handled already)
2007 /* clean up coprocess if needed, on EOF */
2008 coproc_read_close(fd);
2009 if (readmode == READALL)
2010 /* EOF is no error here */
2015 histsave(&source->line, Xstring(xs, xp), true, false);
2017 ccp = cp = Xclose(xs, xp);
2019 XinitN(xs, 128, ATEMP);
2022 if (vp->flag & RDONLY) {
2024 bi_errorf("%s: %s", *wp, "is read only");
2030 /* exporting an array is currently pointless */
2032 /* counter for array index */
2036 /* skip initial IFS whitespace */
2037 while (bytesread && is_ifsws(*ccp)) {
2041 /* trim trailing IFS whitespace */
2042 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
2047 xp = Xstring(xs, xp);
2048 /* generate next word */
2052 goto c_read_splitdone;
2053 /* zero out next parameters */
2054 goto c_read_gotword;
2059 bytesleft = utf_ptradj(ccp);
2060 while (bytesleft && bytesread) {
2065 if (xp[-1] == '\0') {
2069 goto c_read_gotword;
2072 if (!intoarray && wp[1] == NULL)
2076 /* copy until IFS character */
2083 goto c_read_splitcopy;
2084 } else if (ctype(ch, C_IFS)) {
2086 } else if (!rawmode && ch == '\\') {
2096 xsave = Xsavepos(xs, xp);
2097 /* copy word delimiter: IFSWS+IFS,IFSWS */
2102 if (!ctype(ch, C_IFS))
2108 if (!ctype(ch, C_IFSWS))
2111 while (bytesread && is_ifsws(*ccp)) {
2117 /* if no more parameters, rinse and repeat */
2118 if (lastparm && bytesread) {
2120 goto c_read_splitlast;
2122 /* get rid of the delimiter unless we pack the rest */
2124 xp = Xrestpos(xs, xp, xsave);
2128 vq = arraysearch(vp, c++);
2131 /* must be checked before exporting */
2132 if (vq->flag & RDONLY)
2133 goto c_read_splitro;
2135 typeset(*wp, EXPORT, 0, 0, 0);
2137 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
2138 goto c_read_spliterr;
2140 setint_v(vq, vq, false);
2141 /* protect from UTFMODE changes */
2144 if (intoarray || *++wp != NULL)
2145 goto c_read_splitloop;
2152 afree(allocd, ATEMP);
2155 tcsetattr(fd, TCSADRAIN, &tios);
2161 c_eval(const char **wp)
2163 struct source *s, *saves = source;
2164 unsigned char savef;
2167 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2169 s = pushs(SWORDS, ATEMP);
2170 s->u.strv = wp + builtin_opt.optind;
2173 * The following code handles the case where the command is
2174 * empty due to failed command substitution, for example by
2176 * This has historically returned 1 by AT&T ksh88. In this
2177 * case, shell() will not set or change exstat because the
2178 * compiled tree is empty, so it will use the value we pass
2179 * from subst_exstat, which is cleared in execute(), so it
2180 * should have been 0 if there were no substitutions.
2182 * POSIX however says we don't do this, even though it is
2183 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2184 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2186 * 2.9.1: Simple Commands
2187 * ... If there is a command name, execution shall
2188 * continue as described in 2.9.1.1 [Command Search
2189 * and Execution]. If there is no command name, but
2190 * the command contained a command substitution, the
2191 * command shall complete with the exit status of the
2192 * last command substitution performed.
2193 * 2.9.1.1: Command Search and Execution
2194 * (1) a. If the command name matches the name of a
2195 * special built-in utility, that special built-in
2196 * utility shall be invoked.
2198 * If there are no arguments, or only null arguments,
2199 * eval shall return a zero exit status; ...
2201 /* exstat = subst_exstat; */ /* AT&T ksh88 */
2202 exstat = 0; /* SUSv4 */
2204 savef = Flag(FERREXIT);
2206 rv = shell(s, false);
2207 Flag(FERREXIT) = savef;
2214 c_trap(const char **wp)
2220 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2222 wp += builtin_opt.optind;
2225 for (p = sigtraps, i = NSIG+1; --i >= 0; p++)
2226 if (p->trap != NULL) {
2227 shf_puts("trap -- ", shl_stdout);
2228 print_value_quoted(p->trap);
2229 shprintf(" %s\n", p->name);
2235 * Use case sensitive lookup for first arg so the
2236 * command 'exit' isn't confused with the pseudo-signal
2240 s = (gettrap(*wp, false) == NULL) ? *wp++ : NULL;
2241 if (s != NULL && s[0] == '-' && s[1] == '\0')
2244 /* set/clear traps */
2247 if ((p = gettrap(*wp++, true)) == NULL) {
2248 warningf(true, "%s: %s '%s'", builtin_argv0,
2249 "bad signal", wp[-1]);
2257 c_exitreturn(const char **wp)
2262 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2264 arg = wp[builtin_opt.optind];
2267 if (!getn(arg, &n)) {
2269 warningf(true, "%s: %s", arg, "bad number");
2272 } else if (trap_exstat != -1)
2273 exstat = trap_exstat;
2274 if (wp[0][0] == 'r') {
2279 * need to tell if this is exit or return so trap exit will
2280 * work right (POSIX)
2282 for (ep = e; ep; ep = ep->oenv)
2283 if (STOP_RETURN(ep->type)) {
2289 if (how == LEXIT && !really_exit && j_stopped_running()) {
2294 /* get rid of any i/o redirections */
2301 c_brkcont(const char **wp)
2304 struct env *ep, *last_ep = NULL;
2307 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2309 arg = wp[builtin_opt.optind];
2313 else if (!bi_getn(arg, &n))
2317 /* AT&T ksh does this for non-interactive shells only - weird */
2318 bi_errorf("%s: %s", arg, "bad value");
2322 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2323 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2324 if (ep->type == E_LOOP) {
2327 ep->flags |= EF_BRKCONT_PASS;
2333 * AT&T ksh doesn't print a message - just does what it
2334 * can. We print a message 'cause it helps in debugging
2335 * scripts, but don't generate an error (ie, keep going).
2338 warningf(true, "%s: %s %s", wp[0], "can't", wp[0]);
2342 * POSIX says if n is too big, the last enclosing loop
2343 * shall be used. Doesn't say to print an error but we
2344 * do anyway 'cause the user messed up.
2347 last_ep->flags &= ~EF_BRKCONT_PASS;
2348 warningf(true, "%s: can only %s %d level(s)",
2349 wp[0], wp[0], n - quit);
2352 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2357 c_set(const char **wp)
2361 struct block *l = e->loc;
2364 if (wp[1] == NULL) {
2365 static const char *args[] = { Tset, "-", NULL };
2366 return (c_typeset(args));
2369 argi = parse_args(wp, OF_SET, &setargs);
2378 while (*++wp != NULL)
2379 strdupx(*wp, *wp, &l->area);
2380 l->argc = wp - owp - 1;
2381 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2382 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2386 * POSIX says set exit status is 0, but old scripts that use
2387 * getopt(1) use the construct
2388 * set -- $(getopt ab:c "$@")
2389 * which assumes the exit value set will be that of the $()
2390 * (subst_exstat is cleared in execute() so that it will be 0
2391 * if there are no command substitutions).
2392 * Switched ksh (!posix !sh) to POSIX in mksh R39b.
2394 return (Flag(FSH) ? subst_exstat : 0);
2398 c_unset(const char **wp)
2402 bool unset_var = true;
2404 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2413 /*XXX not reached due to GF_ERROR */
2416 wp += builtin_opt.optind;
2417 for (; (id = *wp) != NULL; wp++)
2419 /* unset variable */
2425 if (n > 3 && id[n-3] == '[' && id[n-2] == '*' &&
2427 strndupx(cp, id, n - 3, ATEMP);
2431 optc = vstrchr(id, '[') ? 0 : 1;
2436 if ((vp->flag&RDONLY)) {
2437 warningf(true, "%s: %s", vp->name,
2443 /* unset function */
2449 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2450 const char *prefix, const char *suffix)
2454 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2455 tv_sec, tv_usec, suffix);
2457 shf_fprintf(shf, "%s%*ldm%d.%02ds%s", prefix, width,
2458 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2462 c_times(const char **wp MKSH_A_UNUSED)
2464 struct rusage usage;
2466 getrusage(RUSAGE_SELF, &usage);
2467 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2468 usage.ru_utime.tv_usec, 0, null, " ");
2469 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2470 usage.ru_stime.tv_usec, 0, null, "\n");
2472 getrusage(RUSAGE_CHILDREN, &usage);
2473 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2474 usage.ru_utime.tv_usec, 0, null, " ");
2475 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2476 usage.ru_stime.tv_usec, 0, null, "\n");
2482 * time pipeline (really a statement, not a built-in command)
2485 timex(struct op *t, int f, volatile int *xerrok)
2487 #define TF_NOARGS BIT(0)
2488 #define TF_NOREAL BIT(1) /* don't report real time */
2489 #define TF_POSIX BIT(2) /* report in POSIX format */
2491 struct rusage ru0, ru1, cru0, cru1;
2492 struct timeval usrtime, systime, tv0, tv1;
2494 gettimeofday(&tv0, NULL);
2495 getrusage(RUSAGE_SELF, &ru0);
2496 getrusage(RUSAGE_CHILDREN, &cru0);
2499 * Two ways of getting cpu usage of a command: just use t0
2500 * and t1 (which will get cpu usage from other jobs that
2501 * finish while we are executing t->left), or get the
2502 * cpu usage of t->left. AT&T ksh does the former, while
2503 * pdksh tries to do the later (the j_usrtime hack doesn't
2504 * really work as it only counts the last job).
2506 timerclear(&j_usrtime);
2507 timerclear(&j_systime);
2508 rv = execute(t->left, f | XTIME, xerrok);
2509 if (t->left->type == TCOM)
2510 tf |= t->left->str[0];
2511 gettimeofday(&tv1, NULL);
2512 getrusage(RUSAGE_SELF, &ru1);
2513 getrusage(RUSAGE_CHILDREN, &cru1);
2517 if (tf & TF_NOARGS) {
2518 /* ksh93 - report shell times (shell+kids) */
2520 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2521 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2523 timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
2524 timeradd(&usrtime, &j_usrtime, &usrtime);
2525 timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
2526 timeradd(&systime, &j_systime, &systime);
2529 if (!(tf & TF_NOREAL)) {
2530 timersub(&tv1, &tv0, &tv1);
2532 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2535 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2539 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2542 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2545 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2548 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2549 5, null, " system\n");
2556 timex_hook(struct op *t, char **volatile *app)
2562 ksh_getopt_reset(&opt, 0);
2563 /* start at the start */
2565 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2568 t->str[0] |= TF_POSIX;
2571 errorf("time: -%s %s", opt.optarg,
2574 errorf("time: -%s %s", opt.optarg,
2575 "requires an argument");
2577 /* Copy command words down over options. */
2578 if (opt.optind != 0) {
2579 for (i = 0; i < opt.optind; i++)
2580 afree(wp[i], ATEMP);
2581 for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
2585 t->str[0] |= TF_NOARGS;
2589 /* exec with no args - args case is taken care of in comexec() */
2591 c_exec(const char **wp MKSH_A_UNUSED)
2595 /* make sure redirects stay in place */
2596 if (e->savefd != NULL) {
2597 for (i = 0; i < NUFILE; i++) {
2598 if (e->savefd[i] > 0)
2599 close(e->savefd[i]);
2601 * keep all file descriptors > 2 private for ksh,
2602 * but not for POSIX or legacy/kludge sh
2604 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2606 fcntl(i, F_SETFD, FD_CLOEXEC);
2615 c_mknod(const char **wp)
2617 int argc, optc, rv = 0;
2618 bool ismkfifo = false;
2621 mode_t mode = 0, oldmode = 0;
2623 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2626 set = setmode(builtin_opt.optarg);
2628 bi_errorf("invalid file mode");
2631 mode = getmode(set, (mode_t)(DEFFILEMODE));
2632 free_ossetmode(set);
2638 argv = &wp[builtin_opt.optind];
2639 if (argv[0] == NULL)
2641 for (argc = 0; argv[argc]; argc++)
2643 if (argc == 2 && argv[1][0] == 'p')
2645 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2649 oldmode = umask((mode_t)0);
2653 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2654 (argv[1][0] == 'c') ? S_IFCHR : 0;
2657 unsigned long majnum, minnum;
2661 majnum = strtoul(argv[2], &c, 0);
2662 if ((c == argv[2]) || (*c != '\0')) {
2663 bi_errorf("non-numeric %s %s '%s'", "device", "major", argv[2]);
2666 minnum = strtoul(argv[3], &c, 0);
2667 if ((c == argv[3]) || (*c != '\0')) {
2668 bi_errorf("non-numeric %s %s '%s'", "device", "minor", argv[3]);
2671 dv = makedev(majnum, minnum);
2672 if ((unsigned long)(major(dv)) != majnum) {
2673 bi_errorf("%s %s too large: %lu", "device", "major", majnum);
2676 if ((unsigned long)(minor(dv)) != minnum) {
2677 bi_errorf("%s %s too large: %lu", "device", "minor", minnum);
2680 if (mknod(argv[0], mode, dv))
2681 goto c_mknod_failed;
2682 } else if (mkfifo(argv[0], mode)) {
2684 bi_errorf("%s: %s", argv[0], strerror(errno));
2693 bi_errorf("%s: %s", "usage", "mknod [-m mode] name b|c major minor");
2694 bi_errorf("%s: %s", "usage", "mknod [-m mode] name p");
2700 test(1) accepts the following grammar:
2701 oexpr ::= aexpr | aexpr "-o" oexpr ;
2702 aexpr ::= nexpr | nexpr "-a" aexpr ;
2703 nexpr ::= primary | "!" nexpr ;
2704 primary ::= unary-operator operand
2705 | operand binary-operator operand
2710 unary-operator ::= "-a"|"-r"|"-w"|"-x"|"-e"|"-f"|"-d"|"-c"|"-b"|"-p"|
2711 "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|
2712 "-L"|"-h"|"-S"|"-H";
2714 binary-operator ::= "="|"=="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
2716 "<"|">" # rules used for [[ .. ]] expressions
2718 operand ::= <any thing>
2721 /* POSIX says > 1 for errors */
2722 #define T_ERR_EXIT 2
2725 c_test(const char **wp)
2732 te.getopnd = ptest_getopnd;
2733 te.eval = test_eval;
2734 te.error = ptest_error;
2736 for (argc = 0; wp[argc]; argc++)
2739 if (strcmp(wp[0], "[") == 0) {
2740 if (strcmp(wp[--argc], "]") != 0) {
2741 bi_errorf("missing ]");
2742 return (T_ERR_EXIT);
2747 te.wp_end = wp + argc;
2750 * Handle the special cases from POSIX.2, section 4.62.4.
2751 * Implementation of all the rules isn't necessary since
2752 * our parser does the right thing for the omitted steps.
2755 const char **owp = wp, **owpend = te.wp_end;
2758 const char *opnd1, *opnd2;
2760 if (argc >= 2 && ((*te.isa)(&te, TM_OPAREN))) {
2761 te.pos.wp = te.wp_end - 1;
2762 if ((*te.isa)(&te, TM_CPAREN)) {
2765 te.pos.wp = owp + 2;
2767 te.pos.wp = owp + 1;
2772 while (--argc >= 0) {
2773 if ((*te.isa)(&te, TM_END))
2776 opnd1 = (*te.getopnd)(&te, TO_NONOP, 1);
2777 if ((op = (*te.isa)(&te, TM_BINOP))) {
2778 opnd2 = (*te.getopnd)(&te, op, 1);
2779 res = (*te.eval)(&te, op, opnd1,
2781 if (te.flags & TEF_ERROR)
2782 return (T_ERR_EXIT);
2787 /* back up to opnd1 */
2791 opnd1 = (*te.getopnd)(&te, TO_NONOP, 1);
2792 res = (*te.eval)(&te, TO_STNZE, opnd1,
2798 if ((*te.isa)(&te, TM_NOT)) {
2803 te.pos.wp = owp + 1;
2807 return (test_parse(&te));
2811 * Generic test routines.
2815 test_isop(Test_meta meta, const char *s)
2818 const struct t_op *tbl;
2820 tbl = meta == TM_UNOP ? u_ops : b_ops;
2823 for (; tbl->op_text[0]; tbl++)
2824 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
2825 return (tbl->op_num);
2831 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
2850 return (*opnd1 != '\0');
2854 return (*opnd1 == '\0');
2858 if ((i = *opnd1) == '!' || i == '?')
2860 if ((k = option(opnd1)) == (size_t)-1)
2862 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
2866 /* LINTED use of access */
2867 return (access(opnd1, R_OK) == 0);
2871 /* LINTED use of access */
2872 return (access(opnd1, W_OK) == 0);
2876 return (ksh_access(opnd1, X_OK) == 0);
2882 return (stat(opnd1, &b1) == 0);
2886 return (stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
2890 return (stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
2894 return (stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
2898 return (stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
2902 return (stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
2906 return (lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
2910 return (stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
2912 /* -H => HP context dependent files (directories) */
2919 * Append a + to filename and check to see if result is
2920 * a setuid directory. CDF stuff in general is hookey,
2921 * since it breaks for, e.g., the following sequence:
2922 * echo hi >foo+; mkdir foo; echo bye >foo/default;
2923 * chmod u+s foo (foo+ refers to the file with hi in it,
2924 * there is no way to get at the file with bye in it;
2925 * please correct me if I'm wrong about this).
2928 nv = shf_smprintf("%s+", opnd1);
2929 i = (stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
2939 return (stat(opnd1, &b1) == 0 &&
2940 (b1.st_mode & S_ISUID) == S_ISUID);
2944 return (stat(opnd1, &b1) == 0 &&
2945 (b1.st_mode & S_ISGID) == S_ISGID);
2950 return (stat(opnd1, &b1) == 0 &&
2951 (b1.st_mode & S_ISVTX) == S_ISVTX);
2958 return (stat(opnd1, &b1) == 0 && b1.st_size > 0L);
2962 if (opnd1 && !bi_getn(opnd1, &i)) {
2963 te->flags |= TEF_ERROR;
2966 i = isatty(opnd1 ? i : 0);
2971 return (stat(opnd1, &b1) == 0 && b1.st_uid == ksheuid);
2975 return (stat(opnd1, &b1) == 0 && b1.st_gid == getegid());
2983 if (te->flags & TEF_DBRACKET)
2984 return (gmatchx(opnd1, opnd2, false));
2985 return (strcmp(opnd1, opnd2) == 0);
2989 if (te->flags & TEF_DBRACKET)
2990 return (!gmatchx(opnd1, opnd2, false));
2991 return (strcmp(opnd1, opnd2) != 0);
2995 return (strcmp(opnd1, opnd2) < 0);
2999 return (strcmp(opnd1, opnd2) > 0);
3013 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
3014 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
3015 /* error already printed.. */
3016 te->flags |= TEF_ERROR;
3041 * ksh88/ksh93 succeed if file2 can't be stated
3042 * (subtly different from 'does not exist').
3044 return (stat(opnd1, &b1) == 0 &&
3045 (((s = stat(opnd2, &b2)) == 0 &&
3046 b1.st_mtime > b2.st_mtime) || s < 0));
3051 * ksh88/ksh93 succeed if file1 can't be stated
3052 * (subtly different from 'does not exist').
3054 return (stat(opnd2, &b2) == 0 &&
3055 (((s = stat(opnd1, &b1)) == 0 &&
3056 b1.st_mtime < b2.st_mtime) || s < 0));
3060 return (stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0 &&
3061 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
3063 /* all other cases */
3066 /* throw the error */
3069 (*te->error)(te, 0, "internal error: unknown op");
3074 test_parse(Test_env *te)
3078 rv = test_oexpr(te, 1);
3080 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3081 (*te->error)(te, 0, "unexpected operator/operand");
3083 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3087 test_oexpr(Test_env *te, bool do_eval)
3091 if ((rv = test_aexpr(te, do_eval)))
3093 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3094 return (test_oexpr(te, do_eval) || rv);
3099 test_aexpr(Test_env *te, bool do_eval)
3103 if (!(rv = test_nexpr(te, do_eval)))
3105 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3106 return (test_aexpr(te, do_eval) && rv);
3111 test_nexpr(Test_env *te, bool do_eval)
3113 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3114 return (!test_nexpr(te, do_eval));
3115 return (test_primary(te, do_eval));
3119 test_primary(Test_env *te, bool do_eval)
3121 const char *opnd1, *opnd2;
3125 if (te->flags & TEF_ERROR)
3127 if ((*te->isa)(te, TM_OPAREN)) {
3128 rv = test_oexpr(te, do_eval);
3129 if (te->flags & TEF_ERROR)
3131 if (!(*te->isa)(te, TM_CPAREN)) {
3132 (*te->error)(te, 0, "missing )");
3138 * Binary should have precedence over unary in this case
3139 * so that something like test \( -f = -f \) is accepted
3141 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3142 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3143 if ((op = (*te->isa)(te, TM_UNOP))) {
3144 /* unary expression */
3145 opnd1 = (*te->getopnd)(te, op, do_eval);
3147 (*te->error)(te, -1, "missing argument");
3151 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3154 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3156 (*te->error)(te, 0, "expression expected");
3159 if ((op = (*te->isa)(te, TM_BINOP))) {
3160 /* binary expression */
3161 opnd2 = (*te->getopnd)(te, op, do_eval);
3163 (*te->error)(te, -1, "missing second argument");
3167 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3169 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3173 * Plain test (test and [ .. ]) specific routines.
3177 * Test if the current token is a whatever. Accepts the current token if
3178 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3179 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3182 ptest_isa(Test_env *te, Test_meta meta)
3184 /* Order important - indexed by Test_meta values */
3185 static const char *const tokens[] = {
3186 "-o", "-a", "!", "(", ")"
3190 if (te->pos.wp >= te->wp_end)
3191 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3193 if (meta == TM_UNOP || meta == TM_BINOP)
3194 rv = test_isop(meta, *te->pos.wp);
3195 else if (meta == TM_END)
3198 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3199 TO_NONNULL : TO_NONOP;
3201 /* Accept the token? */
3209 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3211 if (te->pos.wp >= te->wp_end)
3212 return (op == TO_FILTT ? "1" : NULL);
3213 return (*te->pos.wp++);
3217 ptest_error(Test_env *te, int ofs, const char *msg)
3221 te->flags |= TEF_ERROR;
3222 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3223 bi_errorf("%s: %s", op, msg);
3225 bi_errorf("%s", msg);
3228 #ifndef MKSH_NO_LIMITS
3234 int resource; /* resource to get/set */
3235 int factor; /* multiply by to get rlim_{cur,max} values */
3239 static void print_ulimit(const struct limits *, int);
3240 static int set_ulimit(const struct limits *, const char *, int);
3242 /* Magic to divine the 'm' and 'v' limits */
3245 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3246 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3247 #define ULIMIT_V_IS_AS
3248 #elif defined(RLIMIT_VMEM)
3249 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3250 #define ULIMIT_V_IS_AS
3252 #define ULIMIT_V_IS_VMEM
3258 #ifdef ULIMIT_V_IS_VMEM
3259 #define ULIMIT_M_IS_RSS
3260 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3261 #define ULIMIT_M_IS_VMEM
3263 #define ULIMIT_M_IS_RSS
3265 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3266 #undef ULIMIT_M_IS_RSS
3270 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3271 #define ULIMIT_V_IS_VMEM
3274 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3275 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3276 #define ULIMIT_M_IS_VMEM
3279 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3280 (RLIMIT_VMEM == RLIMIT_AS)
3281 #undef ULIMIT_M_IS_VMEM
3286 c_ulimit(const char **wp)
3288 static const struct limits limits[] = {
3289 /* do not use options -H, -S or -a or change the order */
3291 { "time(cpu-seconds)", RLIMIT_CPU, 1, 't' },
3294 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
3297 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
3300 { "data(KiB)", RLIMIT_DATA, 1024, 'd' },
3303 { "stack(KiB)", RLIMIT_STACK, 1024, 's' },
3305 #ifdef RLIMIT_MEMLOCK
3306 { "lockedmem(KiB)", RLIMIT_MEMLOCK, 1024, 'l' },
3308 #ifdef RLIMIT_NOFILE
3309 { "nofiles(descriptors)", RLIMIT_NOFILE, 1, 'n' },
3312 { "processes", RLIMIT_NPROC, 1, 'p' },
3315 { "swap(KiB)", RLIMIT_SWAP, 1024, 'w' },
3318 { "flocks", RLIMIT_LOCKS, -1, 'L' },
3321 { "humantime(seconds)", RLIMIT_TIME, 1, 'T' },
3323 #ifdef RLIMIT_NOVMON
3324 { "vnodemonitors", RLIMIT_NOVMON, 1, 'V' },
3326 #ifdef RLIMIT_SIGPENDING
3327 { "sigpending", RLIMIT_SIGPENDING, 1, 'i' },
3329 #ifdef RLIMIT_MSGQUEUE
3330 { "msgqueue(bytes)", RLIMIT_MSGQUEUE, 1, 'q' },
3332 #ifdef RLIMIT_AIO_MEM
3333 { "AIOlockedmem(KiB)", RLIMIT_AIO_MEM, 1024, 'M' },
3335 #ifdef RLIMIT_AIO_OPS
3336 { "AIOoperations", RLIMIT_AIO_OPS, 1, 'O' },
3338 #ifdef RLIMIT_TCACHE
3339 { "cachedthreads", RLIMIT_TCACHE, 1, 'C' },
3341 #ifdef RLIMIT_SBSIZE
3342 { "sockbufsiz(KiB)", RLIMIT_SBSIZE, 1024, 'B' },
3344 #ifdef RLIMIT_PTHREAD
3345 { "threadsperprocess", RLIMIT_PTHREAD, 1, 'P' },
3348 { "maxnice", RLIMIT_NICE, 1, 'e' },
3350 #ifdef RLIMIT_RTPRIO
3351 { "maxrtprio", RLIMIT_RTPRIO, 1, 'r' },
3353 #if defined(ULIMIT_M_IS_RSS)
3354 { "resident-set(KiB)", RLIMIT_RSS, 1024, 'm' },
3355 #elif defined(ULIMIT_M_IS_VMEM)
3356 { "memory(KiB)", RLIMIT_VMEM, 1024, 'm' },
3358 #if defined(ULIMIT_V_IS_VMEM)
3359 { "virtual-memory(KiB)", RLIMIT_VMEM, 1024, 'v' },
3360 #elif defined(ULIMIT_V_IS_AS)
3361 { "address-space(KiB)", RLIMIT_AS, 1024, 'v' },
3365 static char opts[3 + NELEM(limits)];
3366 int how = SOFT | HARD, optc, what = 'f';
3368 const struct limits *l;
3371 /* build options string on first call - yuck */
3374 *p++ = 'H'; *p++ = 'S'; *p++ = 'a';
3375 for (l = limits; l->name; l++)
3380 while ((optc = ksh_getopt(wp, &builtin_opt, opts)) != -1)
3392 bi_errorf("%s: %s", "usage",
3393 "ulimit [-acdfHLlmnpSsTtvw] [value]");
3399 for (l = limits; l->name && l->option != what; l++)
3402 internal_warningf("ulimit: %c", what);
3406 if (wp[builtin_opt.optind]) {
3407 if (all || wp[builtin_opt.optind + 1]) {
3408 bi_errorf("too many arguments");
3411 return (set_ulimit(l, wp[builtin_opt.optind], how));
3414 print_ulimit(l, how);
3415 else for (l = limits; l->name; l++) {
3416 shprintf("%-20s ", l->name);
3417 print_ulimit(l, how);
3423 set_ulimit(const struct limits *l, const char *v, int how)
3425 rlim_t val = (rlim_t)0;
3426 struct rlimit limit;
3428 if (strcmp(v, "unlimited") == 0)
3429 val = (rlim_t)RLIM_INFINITY;
3433 if (!evaluate(v, &rval, KSH_RETURN_ERROR, false))
3436 * Avoid problems caused by typos that evaluate misses due
3437 * to evaluating unset parameters to 0...
3438 * If this causes problems, will have to add parameter to
3439 * evaluate() to control if unset params are 0 or an error.
3441 if (!rval && !ksh_isdigit(v[0])) {
3442 bi_errorf("invalid %s limit: %s", l->name, v);
3445 val = (rlim_t)((rlim_t)rval * l->factor);
3448 if (getrlimit(l->resource, &limit) < 0) {
3449 /* some can't be read, e.g. Linux RLIMIT_LOCKS */
3450 limit.rlim_cur = RLIM_INFINITY;
3451 limit.rlim_max = RLIM_INFINITY;
3454 limit.rlim_cur = val;
3456 limit.rlim_max = val;
3457 if (!setrlimit(l->resource, &limit))
3460 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3462 bi_errorf("bad %s limit: %s", l->name, strerror(errno));
3467 print_ulimit(const struct limits *l, int how)
3469 rlim_t val = (rlim_t)0;
3470 struct rlimit limit;
3472 if (getrlimit(l->resource, &limit)) {
3473 shf_puts("unknown\n", shl_stdout);
3477 val = limit.rlim_cur;
3478 else if (how & HARD)
3479 val = limit.rlim_max;
3480 if (val == (rlim_t)RLIM_INFINITY)
3481 shf_puts("unlimited\n", shl_stdout);
3483 shprintf("%ld\n", (long)(val / l->factor));
3488 c_rename(const char **wp)
3494 if (wp[0] && !strcmp(wp[0], "--"))
3495 /* skip "--" (options separator) */
3498 /* check for exactly two arguments */
3499 if (wp[0] == NULL /* first argument */ ||
3500 wp[1] == NULL /* second argument */ ||
3501 wp[2] != NULL /* no further args please */)
3503 else if ((rv = rename(wp[0], wp[1])) != 0) {
3505 bi_errorf("%s: %s", "failed", strerror(rv));
3512 c_realpath(const char **wp)
3519 if (wp[0] && !strcmp(wp[0], "--"))
3520 /* skip "--" (options separator) */
3523 /* check for exactly one argument */
3524 if (wp[0] == NULL || wp[1] != NULL)
3526 else if ((buf = do_realpath(wp[0])) == NULL) {
3528 bi_errorf("%s: %s", wp[0], strerror(rv));
3529 if ((unsigned int)rv > 255)
3532 shprintf("%s\n", buf);
3541 c_cat(const char **wp)
3543 int fd = STDIN_FILENO, rv;
3545 const char *fn = "<stdin>";
3547 #define MKSH_CAT_BUFSIZ 4096
3549 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3550 bi_errorf(Toomem, (unsigned long)MKSH_CAT_BUFSIZ);
3554 /* parse options: POSIX demands we support "-u" as no-op */
3555 while ((rv = ksh_getopt(wp, &builtin_opt, "u")) != -1) {
3558 /* we already operate unbuffered */
3565 wp += builtin_opt.optind;
3571 if (fn[0] == '-' && fn[1] == '\0')
3573 else if ((fd = open(fn, O_RDONLY)) < 0) {
3575 bi_errorf("%s: %s", fn, strerror(rv));
3580 while (/* CONSTCOND */ 1) {
3581 n = blocking_read(fd, (cp = buf), MKSH_CAT_BUFSIZ);
3583 if (errno == EINTR) {
3584 /* give the user a chance to ^C out */
3586 /* interrupted, try again */
3589 /* an error occured during reading */
3591 bi_errorf("%s: %s", fn, strerror(rv));
3595 /* end of file reached */
3598 w = write(STDOUT_FILENO, cp, n);
3601 /* interrupted, try again */
3603 /* an error occured during writing */
3605 bi_errorf("%s: %s", "<stdout>",
3608 if (fd != STDIN_FILENO)
3616 if (fd != STDIN_FILENO)
3627 c_sleep(const char **wp)
3634 if (wp[0] && !strcmp(wp[0], "--"))
3635 /* skip "--" (options separator) */
3638 if (!wp[0] || wp[1])
3640 else if (parse_usec(wp[0], &tv))
3641 bi_errorf("%s: %s '%s'", Tsynerr, strerror(errno), wp[0]);
3643 #ifndef MKSH_NOPROSPECTOFWORK
3646 /* block SIGCHLD from interrupting us, though */
3647 sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
3649 if (select(0, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3651 * strictly speaking only for SIGALRM, but the
3652 * execution may be interrupted by other signals
3656 bi_errorf("%s: %s", Tselect, strerror(errno));
3657 #ifndef MKSH_NOPROSPECTOFWORK
3658 sigprocmask(SIG_SETMASK, &omask, NULL);
3665 #if defined(ANDROID)
3667 c_android_lsmod(const char **wp MKSH_A_UNUSED)
3669 const char *cwp[3] = { "cat", "/proc/modules", NULL };
3671 builtin_argv0 = cwp[0];
3672 return (c_cat(cwp));