1 /* $OpenBSD: c_ksh.c,v 1.37 2015/09/10 22:48:58 nicm Exp $ */
2 /* $OpenBSD: c_sh.c,v 1.46 2015/07/20 20:46:24 guenther Exp $ */
3 /* $OpenBSD: c_test.c,v 1.18 2009/03/01 20:11:06 otto Exp $ */
4 /* $OpenBSD: c_ulimit.c,v 1.19 2013/11/28 10:33:37 sobrado Exp $ */
7 * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
8 * 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017
9 * mirabilos <m@mirbsd.org>
11 * Provided that these terms and disclaimer and all copyright notices
12 * are retained or reproduced in an accompanying document, permission
13 * is granted to deal in this work without restriction, including un-
14 * limited rights to use, publicly perform, distribute, sell, modify,
15 * merge, give away, or sublicence.
17 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
18 * the utmost extent permitted by applicable law, neither express nor
19 * implied; without malicious intent or gross negligence. In no event
20 * may a licensor, author or contributor be held liable for indirect,
21 * direct, other damage, loss, or other issues arising in any way out
22 * of dealing in the work, even if advised of the possibility of such
23 * damage or existence of a defect, except proven that it results out
24 * of said person's immediate fault when using the work as intended.
30 #if HAVE_SYS_BSDTYPES_H
31 #include <sys/bsdtypes.h>
34 #include <sys/select.h>
41 __RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.355 2018/10/20 21:04:28 tg Exp $");
45 * use killpg if < -1 since -1 does special things
46 * for some non-killpg-endowed kills
48 #define mksh_kill(p,s) ((p) < -1 ? killpg(-(p), (s)) : kill((p), (s)))
50 /* cross fingers and hope kill is killpg-endowed */
51 #define mksh_kill kill
54 /* XXX conditions correct? */
55 #if !defined(RLIM_INFINITY) && !defined(MKSH_NO_LIMITS)
56 #define MKSH_NO_LIMITS 1
60 #define c_ulimit c_true
63 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
64 static int c_suspend(const char **);
67 static int do_whence(const char **, int, bool, bool);
69 /* getn() that prints error */
71 bi_getn(const char *as, int *ai)
75 if (!(rv = getn(as, ai)))
76 bi_errorf(Tf_sD_s, Tbadnum, as);
81 c_true(const char **wp MKSH_A_UNUSED)
87 c_false(const char **wp MKSH_A_UNUSED)
93 * A leading = means assignments before command are kept.
94 * A leading * means a POSIX special builtin.
95 * A leading ^ means declaration utility, - forwarder.
97 const struct builtin mkshbuiltins[] = {
101 /* no =: AT&T manual wrong */
103 {Tsgbreak, c_brkcont},
104 {T__builtin, c_builtin},
105 {Tbuiltin, c_builtin},
106 #if !defined(__ANDROID__)
110 /* dash compatibility hack */
112 {T_command, c_command},
113 {Tsgcontinue, c_brkcont},
117 {"*=exit", c_exitreturn},
118 {Tdsgexport, c_typeset},
121 {Tgetopts, c_getopts},
122 /* deprecated, replaced by typeset -g */
123 {"^=global", c_typeset},
130 {Tdsgreadonly, c_typeset},
131 #if !defined(__ANDROID__)
132 {"!realpath", c_realpath},
134 {"~rename", c_rename},
135 {"*=return", c_exitreturn},
137 {"*=shift", c_shift},
139 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
140 {Tsuspend, c_suspend},
143 {"*=times", c_times},
146 {Tdgtypeset, c_typeset},
147 {"ulimit", c_ulimit},
149 {Tunalias, c_unalias},
150 {"*=unset", c_unset},
152 {"whence", c_whence},
153 #ifndef MKSH_UNEMPLOYED
157 #ifndef MKSH_NO_CMDLINE_EDITING
163 #ifdef MKSH_PRINTF_BUILTIN
164 {"~printf", c_printf},
167 #if !defined(__ANDROID__)
172 /* alias to "true" for historical reasons */
173 {"domainname", c_true},
178 {NULL, (int (*)(const char **))NULL}
186 static const struct t_op {
217 static const struct t_op b_ops[] = {
235 static int test_oexpr(Test_env *, bool);
236 static int test_aexpr(Test_env *, bool);
237 static int test_nexpr(Test_env *, bool);
238 static int test_primary(Test_env *, bool);
239 static Test_op ptest_isa(Test_env *, Test_meta);
240 static const char *ptest_getopnd(Test_env *, Test_op, bool);
241 static void ptest_error(Test_env *, int, const char *);
242 static void kill_fmt_entry(char *, size_t, unsigned int, const void *);
243 static void p_time(struct shf *, bool, long, int, int,
244 const char *, const char *);
247 c_pwd(const char **wp)
250 bool physical = tobool(Flag(FPHYSICAL));
251 char *p, *allocd = NULL;
253 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
264 wp += builtin_opt.optind;
267 bi_errorf(Ttoo_many_args);
270 p = current_wd[0] ? (physical ? allocd = do_realpath(current_wd) :
272 /* LINTED use of access */
273 if (p && access(p, R_OK) < 0)
275 if (!p && !(p = allocd = ksh_get_wd())) {
276 bi_errorf(Tf_sD_s, "can't determine current directory",
281 afree(allocd, ATEMP);
285 static const char *s_ptr;
286 static int s_get(void);
287 static void s_put(int);
290 c_print(const char **wp)
297 /* storage for columnisation */
299 /* temporary storage for a wide character */
301 /* output file descriptor (if any) */
303 /* temporary storage for a multibyte character */
305 /* output word separator */
307 /* output line separator */
309 /* output a trailing line separator? */
311 /* expand backslash sequences? */
313 /* columnise output? */
315 /* print to history instead of file descriptor / stdout? */
317 /* print words as wide characters? */
319 /* writing to a coprocess (SIGPIPE blocked)? */
324 memset(&po, 0, sizeof(po));
330 if (wp[0][0] == 'e') {
333 #ifndef MKSH_MIDNIGHTBSD01ASH_COMPAT
337 /* BSD "echo" cmd, Debian Policy 10.4 compliant */
340 if (*wp && !strcmp(*wp, "-n")) {
346 bool new_exp, new_nl = true;
349 * compromise between various historic echos: only
350 * recognise -Een if they appear in arguments with
351 * no illegal options; e.g. echo -nq outputs '-nq'
353 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
354 /* MidnightBSD /bin/sh needs -e supported but off */
359 /* otherwise compromise on -e enabled by default */
361 goto print_tradparse_beg;
364 if ((s = *wp) && *s++ == '-' && *s) {
366 switch ((c = *s++)) {
369 goto print_tradparse_ch;
372 goto print_tradparse_ch;
375 goto print_tradparse_ch;
381 goto print_tradparse_arg;
386 /* "print" builtin */
387 const char *opts = "AcelNnpRrsu,";
392 while ((c = ksh_getopt(wp, &builtin_opt, opts)) != -1)
414 if ((po.fd = coproc_getfd(W_OK, &emsg)) < 0) {
415 bi_errorf(Tf_coproc, emsg);
420 /* fake BSD echo but don't reset other flags */
421 wp += builtin_opt.optind;
430 if (!*(s = builtin_opt.optarg))
432 else if ((po.fd = check_fd(s, W_OK, &emsg)) < 0) {
433 bi_errorf("-u%s: %s", s, emsg);
441 if (!(builtin_opt.info & GI_MINUSMINUS)) {
442 /* treat a lone "-" like "--" */
443 if (wp[builtin_opt.optind] &&
444 ksh_isdash(wp[builtin_opt.optind]))
445 builtin_opt.optind++;
447 wp += builtin_opt.optind;
454 XPinit(po.words, 16);
457 Xinit(xs, xp, 128, ATEMP);
463 while (*wp != NULL) {
467 if (!evaluate(s, &po.wc, KSH_RETURN_ERROR, true))
471 po.ts[utf_wctomb(po.ts, po.wc)] = 0;
474 Xput(xs, xp, po.ts[c]);
475 } while (po.ts[++c]);
477 Xput(xs, xp, po.wc & 0xFF);
481 while ((c = *s++) != '\0') {
483 if (po.exp && c == '\\') {
485 c = unbksl(false, s_get, s_put);
488 /* rejected by generic function */
489 switch ((c = *s++)) {
492 /* AT&T brain damage */
501 } else if ((unsigned int)c > 0xFF) {
502 /* generic function returned UCS */
503 po.ts[utf_wctomb(po.ts, c - 0x100)] = 0;
506 Xput(xs, xp, po.ts[c]);
507 } while (po.ts[++c]);
516 XPput(po.words, Xclose(xs, xp));
517 Xinit(xs, xp, 128, ATEMP);
525 size_t w = XPsize(po.words);
526 struct columnise_opts co;
528 XPput(po.words, NULL);
529 co.shf = shf_sopen(NULL, 128, SHF_WR | SHF_DYNAMIC, NULL);
531 co.prefcol = co.do_last = false;
532 pr_list(&co, (char **)XPptrv(po.words));
534 afree(XPptrv(po.words)[w], ATEMP);
536 w = co.shf->wp - co.shf->buf;
538 memcpy(xp, co.shf->buf, w);
549 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
551 size_t len = Xlength(xs, xp);
554 * Ensure we aren't killed by a SIGPIPE while writing to
555 * a coprocess. AT&T ksh doesn't seem to do this (seems
556 * to just check that the co-process is alive which is
559 if (coproc.write >= 0 && coproc.write == po.fd) {
561 po.copipe = block_pipe();
563 po.coproc = po.copipe = false;
569 if ((nwritten = write(po.fd, s, len)) < 0) {
570 if (errno == EINTR) {
573 /* give the user a chance to ^C out */
575 /* interrupted, try again */
577 po.copipe = block_pipe();
597 return (ord(*s_ptr++));
601 s_put(int c MKSH_A_UNUSED)
607 c_whence(const char **wp)
610 bool pflag = false, vflag = false;
612 while ((optc = ksh_getopt(wp, &builtin_opt, Tpv)) != -1)
623 wp += builtin_opt.optind;
625 return (do_whence(wp, pflag ? FC_PATH :
626 FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, false));
629 /* note: command without -vV is dealt with in comexec() */
631 c_command(const char **wp)
633 int optc, fcflags = FC_BI | FC_FUNC | FC_PATH | FC_WHENCE;
636 while ((optc = ksh_getopt(wp, &builtin_opt, TpVv)) != -1)
639 fcflags |= FC_DEFPATH;
650 wp += builtin_opt.optind;
652 return (do_whence(wp, fcflags, vflag, true));
656 do_whence(const char **wp, int fcflags, bool vflag, bool iscommand)
663 while ((vflag || rv == 0) && (id = *wp++) != NULL) {
667 if (fcflags & FC_WHENCE)
668 tp = ktsearch(&keywords, id, h);
669 if (!tp && (fcflags & FC_WHENCE)) {
670 tp = ktsearch(&aliases, id, h);
671 if (tp && !(tp->flag & ISSET))
675 tp = findcom(id, fcflags);
681 shf_puts(id, shl_stdout);
688 shprintf(" is a %sshell %s",
689 (tp->flag & SPEC_BI) ? "special " : "",
694 shf_puts(" is a", shl_stdout);
695 if (tp->flag & EXPORT)
696 shf_puts("n exported", shl_stdout);
697 if (tp->flag & TRACE)
698 shf_puts(" traced", shl_stdout);
699 if (!(tp->flag & ISSET)) {
700 shf_puts(" undefined", shl_stdout);
702 shprintf(" (autoload from %s)",
705 shf_puts(T_function, shl_stdout);
710 if (tp->flag & ISSET) {
712 shprintf("%s is ", id);
713 if (tp->type == CTALIAS)
714 shprintf("a tracked %s%s for ",
715 (tp->flag & EXPORT) ?
719 shf_puts(tp->val.s, shl_stdout);
722 shprintf(Tnot_found_s, id);
728 shprintf("%s is an %s%s for ", id,
729 (tp->flag & EXPORT) ? "exported " : "",
731 } else if (iscommand)
732 shprintf("%s %s=", Talias, id);
733 print_value_quoted(shl_stdout, tp->val.s);
737 shf_puts(" is a reserved word", shl_stdout);
741 bi_errorf(Tunexpected_type, id, Tcommand, tp->type);
746 shf_putc('\n', shl_stdout);
752 valid_alias_name(const char *cp)
754 if (ord(*cp) == ORD('-'))
756 if (ord(cp[0]) == ORD('[') && ord(cp[1]) == ORD('[') && !cp[2])
759 if (ctype(*cp, C_ALIAS))
767 c_alias(const char **wp)
769 struct table *t = &aliases;
770 int rv = 0, prefix = 0;
771 bool rflag = false, tflag, Uflag = false, pflag = false, chkalias;
775 builtin_opt.flags |= GF_PLUSOPT;
776 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
777 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
781 t = NULL; /* fix "alias -dt" */
797 * kludge for tracked alias initialization
798 * (don't do a path search, just make an entry)
813 wp += builtin_opt.optind;
815 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
816 ctype(wp[0][0], C_MINUS | C_PLUS) && wp[0][1] == '\0') {
821 tflag = t == &taliases;
822 chkalias = t == &aliases;
824 /* "hash -r" means reset all the tracked aliases.. */
826 static const char *args[] = {
827 Tunalias, "-ta", NULL
831 shprintf("%s: -r flag can only be used with -t"
832 " and without arguments\n", Talias);
835 ksh_getopt_reset(&builtin_opt, GF_ERROR);
836 return (c_unalias(args));
842 for (p = ktsort(t); (ap = *p++) != NULL; )
843 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
845 shprintf(Tf_s_, Talias);
846 shf_puts(ap->name, shl_stdout);
848 shf_putc('=', shl_stdout);
849 print_value_quoted(shl_stdout, ap->val.s);
851 shf_putc('\n', shl_stdout);
855 for (; *wp != NULL; wp++) {
856 const char *alias = *wp, *val, *newval;
861 if ((val = cstrchr(alias, '='))) {
862 strndupx(xalias, alias, val++ - alias, ATEMP);
865 if (chkalias && !valid_alias_name(alias)) {
866 bi_errorf(Tinvname, alias, Talias);
867 afree(xalias, ATEMP);
871 if (val == NULL && !tflag && !xflag) {
872 ap = ktsearch(t, alias, h);
873 if (ap != NULL && (ap->flag&ISSET)) {
875 shprintf(Tf_s_, Talias);
876 shf_puts(ap->name, shl_stdout);
878 shf_putc('=', shl_stdout);
879 print_value_quoted(shl_stdout, ap->val.s);
881 shf_putc('\n', shl_stdout);
883 shprintf(Tf_s_s_sN, alias, Talias, Tnot_found);
888 ap = ktenter(t, alias, h);
889 ap->type = tflag ? CTALIAS : CALIAS;
890 /* Are we setting the value or just some flags? */
891 if ((val && !tflag) || (!val && tflag && !Uflag)) {
892 if (ap->flag&ALLOC) {
893 ap->flag &= ~(ALLOC|ISSET);
894 afree(ap->val.s, APERM);
896 /* ignore values for -t (AT&T ksh does this) */
898 search_path(alias, path, X_OK, NULL) :
901 strdupx(ap->val.s, newval, APERM);
902 ap->flag |= ALLOC|ISSET;
911 afree(xalias, ATEMP);
918 c_unalias(const char **wp)
920 struct table *t = &aliases;
925 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
932 /* fix "unalias -dt" */
948 wp += builtin_opt.optind;
950 for (; *wp != NULL; wp++) {
951 ap = ktsearch(t, *wp, hash(*wp));
957 if (ap->flag&ALLOC) {
958 ap->flag &= ~(ALLOC|ISSET);
959 afree(ap->val.s, APERM);
961 ap->flag &= ~(DEFINED|ISSET|EXPORT);
967 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
968 if (ap->flag&ALLOC) {
969 ap->flag &= ~(ALLOC|ISSET);
970 afree(ap->val.s, APERM);
972 ap->flag &= ~(DEFINED|ISSET|EXPORT);
980 c_let(const char **wp)
986 /* AT&T ksh does this */
989 for (wp++; *wp; wp++)
990 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
991 /* distinguish error from zero result */
1000 c_jobs(const char **wp)
1002 int optc, flag = 0, nflag = 0, rv = 0;
1004 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1016 /* debugging: print zombies */
1022 wp += builtin_opt.optind;
1024 if (j_jobs(NULL, flag, nflag))
1028 if (j_jobs(*wp, flag, nflag))
1034 #ifndef MKSH_UNEMPLOYED
1036 c_fgbg(const char **wp)
1038 bool bg = strcmp(*wp, Tbg) == 0;
1041 if (!Flag(FMONITOR)) {
1042 bi_errorf("job control not enabled");
1045 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1047 wp += builtin_opt.optind;
1050 rv = j_resume(*wp, bg);
1052 rv = j_resume("%%", bg);
1053 /* fg returns $? of the job unless POSIX */
1054 return ((bg | Flag(FPOSIX)) ? 0 : rv);
1058 /* format a single kill item */
1060 kill_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1062 const struct kill_info *ki = (const struct kill_info *)arg;
1065 shf_snprintf(buf, buflen, "%*u %*s %s",
1067 ki->name_width, sigtraps[i].name,
1072 c_kill(const char **wp)
1079 /* assume old style options if -digits or -UPPERCASE */
1080 if ((p = wp[1]) && *p == '-' && ctype(p[1], C_DIGIT | C_UPPER)) {
1081 if (!(t = gettrap(p + 1, false, false))) {
1082 bi_errorf(Tbad_sig_s, p + 1);
1085 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1089 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1095 if (!(t = gettrap(builtin_opt.optarg,
1097 bi_errorf(Tbad_sig_s,
1098 builtin_opt.optarg);
1105 i = builtin_opt.optind;
1107 if ((lflag && t) || (!wp[i] && !lflag)) {
1109 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1110 " { job | pid | pgrp } ...\n"
1111 "\tkill -l [exit_status ...]\n", shl_out);
1119 for (; wp[i]; i++) {
1120 if (!bi_getn(wp[i], &n))
1122 #if (ksh_NSIG <= 128)
1123 if (n > 128 && n < 128 + ksh_NSIG)
1126 if (n > 0 && n < ksh_NSIG)
1127 shprintf(Tf_sN, sigtraps[n].name);
1131 } else if (Flag(FPOSIX)) {
1133 while (n < ksh_NSIG) {
1134 shf_puts(sigtraps[n].name, shl_stdout);
1135 shf_putc(++n == ksh_NSIG ? '\n' : ' ',
1139 ssize_t w, mess_cols = 0, mess_octs = 0;
1140 int j = ksh_NSIG - 1;
1141 struct kill_info ki = { 0, 0 };
1142 struct columnise_opts co;
1146 } while ((j /= 10));
1148 for (j = 1; j < ksh_NSIG; j++) {
1149 w = strlen(sigtraps[j].name);
1150 if (w > ki.name_width)
1152 w = strlen(sigtraps[j].mess);
1155 w = utf_mbswidth(sigtraps[j].mess);
1160 co.shf = shl_stdout;
1162 co.prefcol = co.do_last = true;
1164 print_columns(&co, (unsigned int)(ksh_NSIG - 1),
1165 kill_fmt_entry, (void *)&ki,
1166 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1167 ki.num_width + 1 + ki.name_width + 1 + mess_cols);
1172 sig = t ? t->signal : SIGTERM;
1173 for (; (p = wp[i]); i++) {
1177 } else if (!getn(p, &n)) {
1178 bi_errorf(Tf_sD_s, p,
1179 "arguments must be jobs or process IDs");
1182 if (mksh_kill(n, sig) < 0) {
1183 bi_errorf(Tf_sD_s, p, cstrerror(errno));
1192 getopts_reset(int val)
1195 ksh_getopt_reset(&user_opt, GF_NONAME |
1196 (Flag(FPOSIX) ? 0 : GF_PLUSOPT));
1197 user_opt.optind = user_opt.uoptind = val;
1202 c_getopts(const char **wp)
1205 const char *opts, *var;
1207 struct tbl *vq, *voptarg;
1209 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1211 wp += builtin_opt.optind;
1215 bi_errorf(Tf_sD_s, "options", Tno_args);
1221 bi_errorf(Tf_sD_s, Tname, Tno_args);
1224 if (!*var || *skip_varname(var, true)) {
1225 bi_errorf(Tf_sD_s, var, Tnot_ident);
1229 if (e->loc->next == NULL) {
1230 internal_warningf(Tf_sD_s, Tgetopts, Tno_args);
1233 /* Which arguments are we parsing... */
1235 wp = e->loc->next->argv;
1237 *--wp = e->loc->next->argv[0];
1239 /* Check that our saved state won't cause a core dump... */
1240 for (argc = 0; wp[argc]; argc++)
1242 if (user_opt.optind > argc ||
1244 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1245 bi_errorf("arguments changed since last call");
1249 user_opt.optarg = NULL;
1250 optc = ksh_getopt(wp, &user_opt, opts);
1252 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1258 * POSIX says var is set to ? at end-of-options, AT&T ksh
1259 * sets it to null - we go with POSIX...
1261 buf[0] = optc < 0 ? '?' : optc;
1265 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1266 user_opt.uoptind = user_opt.optind;
1268 voptarg = global("OPTARG");
1269 /* AT&T ksh clears ro and int */
1270 voptarg->flag &= ~RDONLY;
1271 /* Paranoia: ensure no bizarre results. */
1272 if (voptarg->flag & INTEGER)
1273 typeset("OPTARG", 0, INTEGER, 0, 0);
1274 if (user_opt.optarg == NULL)
1277 /* this can't fail (haing cleared readonly/integer) */
1278 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1283 /* Error message already printed (integer, readonly) */
1284 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1287 typeset(var, EXPORT, 0, 0, 0);
1289 return (optc < 0 ? 1 : rv);
1292 #ifndef MKSH_NO_CMDLINE_EDITING
1294 c_bind(const char **wp)
1304 while ((optc = ksh_getopt(wp, &builtin_opt,
1323 wp += builtin_opt.optind;
1327 rv = x_bind(NULL, NULL,
1333 for (; *wp != NULL; wp++) {
1334 if ((cp = cstrchr(*wp, '=')) == NULL)
1337 strdupx(up, *wp, ATEMP);
1338 up[cp++ - *wp] = '\0';
1340 if (x_bind(up ? up : *wp, cp,
1354 c_shift(const char **wp)
1356 struct block *l = e->loc;
1361 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1363 arg = wp[builtin_opt.optind];
1367 else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
1368 /* error already printed */
1371 } else if (!(n = val)) {
1375 bi_errorf(Tf_sD_s, Tbadnum, arg);
1379 bi_errorf("nothing to shift");
1382 l->argv[n] = l->argv[0];
1389 c_umask(const char **wp)
1393 bool symbolic = false;
1396 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1404 cp = wp[builtin_opt.optind];
1406 old_umask = umask((mode_t)0);
1412 old_umask = ~old_umask;
1414 for (i = 0; i < 3; i++) {
1417 for (j = 0; j < 3; j++)
1418 if (old_umask & (1 << (8 - (3*i + j))))
1423 shprintf(Tf_sN, buf);
1425 shprintf("%#3.3o\n", (unsigned int)old_umask);
1429 if (ctype(*cp, C_DIGIT)) {
1431 while (ctype(*cp, C_OCTAL)) {
1432 new_umask = new_umask * 8 + ksh_numdig(*cp);
1440 /* symbolic format */
1441 int positions, new_val;
1444 old_umask = umask((mode_t)0);
1445 /* in case of error */
1447 old_umask = ~old_umask;
1448 new_umask = old_umask;
1451 while (*cp && vstrchr(Taugo, *cp))
1469 if (!ctype((op = *cp), C_EQUAL | C_MINUS | C_PLUS))
1473 while (*cp && vstrchr("rwxugoXs", *cp))
1475 case 'r': new_val |= 04; break;
1476 case 'w': new_val |= 02; break;
1477 case 'x': new_val |= 01; break;
1479 new_val |= old_umask >> 6;
1482 new_val |= old_umask >> 3;
1485 new_val |= old_umask >> 0;
1488 if (old_umask & 0111)
1495 new_val = (new_val & 07) * positions;
1498 new_umask &= ~new_val;
1501 new_umask = new_val |
1502 (new_umask & ~(positions * 07));
1505 new_umask |= new_val;
1510 } else if (!ctype(*cp, C_EQUAL | C_MINUS | C_PLUS))
1514 bi_errorf("bad mask");
1517 new_umask = ~new_umask;
1525 c_dot(const char **wp)
1527 const char *file, *cp, **argv;
1528 int argc, rv, errcode;
1530 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1533 if ((cp = wp[builtin_opt.optind]) == NULL) {
1534 bi_errorf(Tno_args);
1537 file = search_path(cp, path, R_OK, &errcode);
1538 if (!file && errcode == ENOENT && wp[0][0] == 's' &&
1539 search_access(cp, R_OK) == 0)
1542 bi_errorf(Tf_sD_s, cp, cstrerror(errcode));
1546 /* Set positional parameters? */
1547 if (wp[builtin_opt.optind + 1]) {
1548 argv = wp + builtin_opt.optind;
1550 argv[0] = e->loc->argv[0];
1551 for (argc = 0; argv[argc + 1]; argc++)
1557 /* SUSv4: OR with a high value never written otherwise */
1559 if ((rv = include(file, argc, argv, false)) < 0) {
1560 /* should not happen */
1561 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
1564 if (exstat & 0x4000)
1565 /* detect old exstat, use 0 in that case */
1571 c_wait(const char **wp)
1575 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1577 wp += builtin_opt.optind;
1579 while (waitfor(NULL, &sig) >= 0)
1584 rv = waitfor(*wp, &sig);
1586 /* magic exit code: bad job-id */
1587 rv = sig ? sig : 127;
1592 static const char REPLY[] = "REPLY";
1594 c_read(const char **wp)
1596 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1597 int c, fd = 0, rv = 0;
1598 bool savehist = false, intoarray = false, aschars = false;
1599 bool rawmode = false, expanding = false;
1600 bool lastparmmode = false, lastparmused = false;
1601 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1603 size_t bytesleft = 128, bytesread;
1604 struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
1605 char *cp, *allocd = NULL, *xp;
1610 bool restore_tios = false;
1611 /* to catch read -aN2 foo[i] */
1612 bool subarray = false;
1614 bool hastimeout = false;
1615 struct timeval tv, tvlim;
1616 #define c_read_opts "Aad:N:n:prst:u,"
1618 #define c_read_opts "Aad:N:n:prsu,"
1620 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1625 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1634 delim = builtin_opt.optarg[0];
1638 readmode = c == 'N' ? BYTES : UPTO;
1639 if (!bi_getn(builtin_opt.optarg, &c))
1642 readmode = readmode == BYTES ? READALL : UPTO;
1645 bytesleft = (unsigned int)c;
1648 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1649 bi_errorf(Tf_coproc, ccp);
1661 if (parse_usec(builtin_opt.optarg, &tv)) {
1662 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno),
1663 builtin_opt.optarg);
1670 if (!builtin_opt.optarg[0])
1672 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1673 bi_errorf(Tf_sD_sD_s, "-u", builtin_opt.optarg, ccp);
1680 wp += builtin_opt.optind;
1684 if (intoarray && wp[1] != NULL) {
1685 bi_errorf(Ttoo_many_args);
1689 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1690 strdupx(allocd, *wp, ATEMP);
1691 allocd[ccp - *wp] = '\0';
1695 * AT&T ksh says it prints prompt on fd if it's open
1696 * for writing and is a tty, but it doesn't do it
1697 * (it also doesn't check the interactive flag,
1698 * as is indicated in the Korn Shell book).
1700 shf_puts(ccp + 1, shl_out);
1705 Xinit(xs, xp, bytesleft, ATEMP);
1707 if (readmode == LINES)
1709 else if (isatty(fd)) {
1710 x_mkraw(fd, &tios, true);
1711 restore_tios = true;
1717 timeradd(&tvlim, &tv, &tvlim);
1727 FD_SET((unsigned int)fd, &fdset);
1729 timersub(&tvlim, &tv, &tv);
1730 if (tv.tv_sec < 0) {
1731 /* timeout expired globally */
1736 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
1740 /* timeout expired for this call */
1743 goto c_read_readdone;
1745 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
1752 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1753 saved_mode = setmode(fd, O_TEXT);
1755 if ((bytesread = blocking_read(fd, xp, bytesleft)) == (size_t)-1) {
1756 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1757 saved_errno = errno;
1758 setmode(fd, saved_mode);
1759 errno = saved_errno;
1761 if (errno == EINTR) {
1762 /* check whether the signal would normally kill */
1763 if (!fatal_trap_check()) {
1764 /* no, just ignore the signal */
1765 goto c_read_readloop;
1767 /* pretend the read was killed */
1769 /* unexpected error */
1770 bi_errorf(Tf_s, cstrerror(errno));
1775 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1776 setmode(fd, saved_mode);
1781 if (bytesread == 0) {
1782 /* end of file reached */
1784 goto c_read_readdone;
1787 XcheckN(xs, xp, bytesleft);
1792 /* end of file reached */
1795 goto c_read_readdone;
1798 if (bytesread == 0) {
1799 /* end of file reached */
1801 /* may be partial read: $? = 1, but content */
1802 goto c_read_readdone;
1805 if ((bytesleft -= bytesread) == 0)
1806 goto c_read_readdone;
1809 if (bytesread == 0) {
1810 /* end of file reached */
1812 goto c_read_readdone;
1814 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
1815 /* skip any read NULs unless delimiter */
1821 if (Flag(FTALKING_I) && isatty(fd)) {
1823 * set prompt in case this is
1824 * called from .profile or $ENV
1826 set_prompt(PS2, NULL);
1829 /* drop the backslash */
1831 /* and the delimiter */
1834 } else if (c == delim) {
1835 goto c_read_readdone;
1836 } else if (!rawmode && c == '\\') {
1843 goto c_read_readloop;
1846 bytesread = Xlength(xs, xp);
1850 * state: we finished reading the input and NUL terminated it
1851 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
1852 * rv = 3 if timeout, 1 if EOF, 0 otherwise (errors handled already)
1856 /* clean up coprocess if needed, on EOF/error/timeout */
1857 coproc_read_close(fd);
1858 if (readmode == READALL && (rv == 1 || (rv == 3 && bytesread)))
1859 /* EOF is no error here */
1864 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
1866 ccp = cp = Xclose(xs, xp);
1868 XinitN(xs, 128, ATEMP);
1871 subarray = last_lookup_was_array;
1872 if (vp->flag & RDONLY) {
1874 bi_errorf(Tf_ro, *wp);
1880 /* counter for array index */
1881 c = subarray ? arrayindex(vp) : 0;
1882 /* exporting an array is currently pointless */
1883 unset(vp, subarray ? 0 : 1);
1886 /* skip initial IFS whitespace */
1887 while (bytesread && is_ifsws(*ccp)) {
1891 /* trim trailing IFS whitespace */
1892 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
1897 xp = Xstring(xs, xp);
1898 /* generate next word */
1902 goto c_read_splitdone;
1903 /* zero out next parameters */
1904 goto c_read_gotword;
1909 bytesleft = utf_ptradj(ccp);
1910 while (bytesleft && bytesread) {
1915 if (xp[-1] == '\0') {
1919 goto c_read_gotword;
1922 if (!intoarray && wp[1] == NULL)
1923 lastparmmode = true;
1926 /* copy until IFS character */
1933 goto c_read_splitcopy;
1934 } else if (ctype(ch, C_IFS)) {
1936 } else if (!rawmode && ch == '\\') {
1946 xsave = Xsavepos(xs, xp);
1947 /* copy word delimiter: IFSWS+IFS,IFSWS */
1953 if (!ctype(ch, C_IFS))
1955 if (lastparmmode && !expanding && !rawmode && ch == '\\') {
1965 if (!ctype(ch, C_IFSWS))
1968 while (bytesread && is_ifsws(*ccp)) {
1974 /* if no more parameters, rinse and repeat */
1975 if (lastparmmode && bytesread) {
1976 lastparmused = true;
1977 goto c_read_splitlast;
1979 /* get rid of the delimiter unless we pack the rest */
1981 xp = Xrestpos(xs, xp, xsave);
1986 /* array element passed, accept first read */
1988 bi_errorf("nested arrays not yet supported");
1989 goto c_read_spliterr;
1996 vq = arraysearch(vp, c++);
1999 /* must be checked before exporting */
2000 if (vq->flag & RDONLY)
2001 goto c_read_splitro;
2003 typeset(*wp, EXPORT, 0, 0, 0);
2005 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
2006 goto c_read_spliterr;
2008 setint_v(vq, vq, false);
2009 /* protect from UTFMODE changes */
2012 if (intoarray || *++wp != NULL)
2013 goto c_read_splitloop;
2020 afree(allocd, ATEMP);
2023 mksh_tcset(fd, &tios);
2024 return (rv == 3 ? ksh_sigmask(SIGALRM) : rv);
2029 c_eval(const char **wp)
2031 struct source *s, *saves = source;
2032 unsigned char savef;
2035 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2037 s = pushs(SWORDS, ATEMP);
2038 s->u.strv = wp + builtin_opt.optind;
2039 s->line = current_lineno;
2042 * The following code handles the case where the command is
2043 * empty due to failed command substitution, for example by
2045 * This has historically returned 1 by AT&T ksh88. In this
2046 * case, shell() will not set or change exstat because the
2047 * compiled tree is empty, so it will use the value we pass
2048 * from subst_exstat, which is cleared in execute(), so it
2049 * should have been 0 if there were no substitutions.
2051 * POSIX however says we don't do this, even though it is
2052 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2053 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2055 * 2.9.1: Simple Commands
2056 * ... If there is a command name, execution shall
2057 * continue as described in 2.9.1.1 [Command Search
2058 * and Execution]. If there is no command name, but
2059 * the command contained a command substitution, the
2060 * command shall complete with the exit status of the
2061 * last command substitution performed.
2062 * 2.9.1.1: Command Search and Execution
2063 * (1) a. If the command name matches the name of a
2064 * special built-in utility, that special built-in
2065 * utility shall be invoked.
2067 * If there are no arguments, or only null arguments,
2068 * eval shall return a zero exit status; ...
2070 /* AT&T ksh88: use subst_exstat */
2071 /* exstat = subst_exstat; */
2072 /* SUSv4: OR with a high value never written otherwise */
2075 savef = Flag(FERREXIT);
2076 Flag(FERREXIT) |= 0x80;
2078 Flag(FERREXIT) = savef;
2081 if (exstat & 0x4000)
2082 /* detect old exstat, use 0 in that case */
2088 c_trap(const char **wp)
2094 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2096 wp += builtin_opt.optind;
2101 shf_puts("trap -- ", shl_stdout);
2102 print_value_quoted(shl_stdout, p->trap);
2103 shprintf(Tf__sN, p->name);
2110 if (getn(*wp, &i)) {
2111 /* first argument is a signal number, reset them all */
2114 /* first argument must be a command, then */
2121 /* set/clear the traps */
2124 if (!(p = gettrap(*wp++, true, true))) {
2125 warningf(true, Tbad_sig_ss, builtin_argv0, wp[-1]);
2133 c_exitreturn(const char **wp)
2139 goto c_exitreturn_err;
2140 exstat = bi_getn(wp[1], &n) ? (n & 0xFF) : 1;
2141 } else if (trap_exstat != -1)
2142 exstat = trap_exstat;
2144 if (wp[0][0] == 'r') {
2149 * need to tell if this is exit or return so trap exit will
2150 * work right (POSIX)
2152 for (ep = e; ep; ep = ep->oenv)
2153 if (STOP_RETURN(ep->type)) {
2159 if (how == LEXIT && !really_exit && j_stopped_running()) {
2164 /* get rid of any I/O redirections */
2170 bi_errorf(Ttoo_many_args);
2175 c_brkcont(const char **wp)
2179 struct env *ep, *last_ep = NULL;
2182 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2184 arg = wp[builtin_opt.optind];
2188 else if (!bi_getn(arg, &n))
2191 /* AT&T ksh does this for non-interactive shells only - weird */
2192 bi_errorf("%s: bad value", arg);
2195 quit = (unsigned int)n;
2197 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2198 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2199 if (ep->type == E_LOOP) {
2202 ep->flags |= EF_BRKCONT_PASS;
2208 * AT&T ksh doesn't print a message - just does what it
2209 * can. We print a message 'cause it helps in debugging
2210 * scripts, but don't generate an error (ie, keep going).
2212 if ((unsigned int)n == quit) {
2213 warningf(true, Tf_cant_s, wp[0], wp[0]);
2217 * POSIX says if n is too big, the last enclosing loop
2218 * shall be used. Doesn't say to print an error but we
2219 * do anyway 'cause the user messed up.
2222 last_ep->flags &= ~EF_BRKCONT_PASS;
2223 warningf(true, "%s: can only %s %u level(s)",
2224 wp[0], wp[0], (unsigned int)n - quit);
2227 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2235 c_set(const char **wp)
2239 struct block *l = e->loc;
2242 if (wp[1] == NULL) {
2243 static const char *args[] = { Tset, "-", NULL };
2244 return (c_typeset(args));
2247 if ((argi = parse_args(wp, OF_SET, &setargs)) < 0)
2255 while (*++wp != NULL)
2256 strdupx(*wp, *wp, &l->area);
2257 l->argc = wp - owp - 1;
2258 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2259 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2263 * POSIX says set exit status is 0, but old scripts that use
2264 * getopt(1) use the construct
2265 * set -- $(getopt ab:c "$@")
2266 * which assumes the exit value set will be that of the $()
2267 * (subst_exstat is cleared in execute() so that it will be 0
2268 * if there are no command substitutions).
2270 #ifdef MKSH_LEGACY_MODE
2271 /* traditional behaviour, unless set -o posix */
2272 return (Flag(FPOSIX) ? 0 : subst_exstat);
2274 /* conformant behaviour, unless set -o sh +o posix */
2275 return (Flag(FSH) && !Flag(FPOSIX) ? subst_exstat : 0);
2280 c_unset(const char **wp)
2284 bool unset_var = true;
2286 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2295 /*XXX not reached due to GF_ERROR */
2298 wp += builtin_opt.optind;
2299 for (; (id = *wp) != NULL; wp++)
2301 /* unset variable */
2307 if (n > 3 && ord(id[n - 3]) == ORD('[') &&
2308 ord(id[n - 2]) == ORD('*') &&
2309 ord(id[n - 1]) == ORD(']')) {
2310 strndupx(cp, id, n - 3, ATEMP);
2314 optc = vstrchr(id, '[') ? 0 : 1;
2319 if ((vp->flag&RDONLY)) {
2320 warningf(true, Tf_ro, vp->name);
2325 /* unset function */
2331 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2332 const char *prefix, const char *suffix)
2336 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2337 tv_sec, tv_usec, suffix);
2339 shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
2340 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2344 c_times(const char **wp MKSH_A_UNUSED)
2346 struct rusage usage;
2348 getrusage(RUSAGE_SELF, &usage);
2349 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2350 usage.ru_utime.tv_usec, 0, null, T1space);
2351 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2352 usage.ru_stime.tv_usec, 0, null, "\n");
2354 getrusage(RUSAGE_CHILDREN, &usage);
2355 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2356 usage.ru_utime.tv_usec, 0, null, T1space);
2357 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2358 usage.ru_stime.tv_usec, 0, null, "\n");
2364 * time pipeline (really a statement, not a built-in command)
2367 timex(struct op *t, int f, volatile int *xerrok)
2369 #define TF_NOARGS BIT(0)
2370 #define TF_NOREAL BIT(1) /* don't report real time */
2371 #define TF_POSIX BIT(2) /* report in POSIX format */
2373 struct rusage ru0, ru1, cru0, cru1;
2374 struct timeval usrtime, systime, tv0, tv1;
2377 getrusage(RUSAGE_SELF, &ru0);
2378 getrusage(RUSAGE_CHILDREN, &cru0);
2381 * Two ways of getting cpu usage of a command: just use t0
2382 * and t1 (which will get cpu usage from other jobs that
2383 * finish while we are executing t->left), or get the
2384 * cpu usage of t->left. AT&T ksh does the former, while
2385 * pdksh tries to do the later (the j_usrtime hack doesn't
2386 * really work as it only counts the last job).
2388 timerclear(&j_usrtime);
2389 timerclear(&j_systime);
2390 rv = execute(t->left, f | XTIME, xerrok);
2391 if (t->left->type == TCOM)
2392 tf |= t->left->str[0];
2394 getrusage(RUSAGE_SELF, &ru1);
2395 getrusage(RUSAGE_CHILDREN, &cru1);
2399 if (tf & TF_NOARGS) {
2400 /* ksh93 - report shell times (shell+kids) */
2402 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2403 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2405 timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
2406 timeradd(&usrtime, &j_usrtime, &usrtime);
2407 timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
2408 timeradd(&systime, &j_systime, &systime);
2411 if (!(tf & TF_NOREAL)) {
2412 timersub(&tv1, &tv0, &tv1);
2414 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2415 5, Treal_sp1, "\n");
2417 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2418 5, null, Treal_sp2);
2421 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2422 5, Tuser_sp1, "\n");
2424 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2425 5, null, Tuser_sp2);
2427 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2430 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2431 5, null, " system\n");
2438 timex_hook(struct op *t, char **volatile *app)
2444 ksh_getopt_reset(&opt, 0);
2445 /* start at the start */
2447 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2450 t->str[0] |= TF_POSIX;
2453 errorf(Tf_optfoo, Ttime, Tcolsp,
2454 opt.optarg[0], Tunknown_option);
2456 errorf(Tf_optfoo, Ttime, Tcolsp,
2457 opt.optarg[0], Treq_arg);
2459 /* Copy command words down over options. */
2460 if (opt.optind != 0) {
2461 for (i = 0; i < opt.optind; i++)
2462 afree(wp[i], ATEMP);
2463 for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
2467 t->str[0] |= TF_NOARGS;
2471 /* exec with no args - args case is taken care of in comexec() */
2473 c_exec(const char **wp MKSH_A_UNUSED)
2477 /* make sure redirects stay in place */
2478 if (e->savefd != NULL) {
2479 for (i = 0; i < NUFILE; i++) {
2480 if (e->savefd[i] > 0)
2481 close(e->savefd[i]);
2483 * keep all file descriptors > 2 private for ksh,
2484 * but not for POSIX or legacy/kludge sh
2486 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2488 fcntl(i, F_SETFD, FD_CLOEXEC);
2495 #if HAVE_MKNOD && !defined(__OS2__)
2497 c_mknod(const char **wp)
2499 int argc, optc, rv = 0;
2500 bool ismkfifo = false;
2503 mode_t mode = 0, oldmode = 0;
2505 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2508 set = setmode(builtin_opt.optarg);
2510 bi_errorf("invalid file mode");
2513 mode = getmode(set, (mode_t)(DEFFILEMODE));
2514 free_ossetmode(set);
2520 argv = &wp[builtin_opt.optind];
2521 if (argv[0] == NULL)
2523 for (argc = 0; argv[argc]; argc++)
2525 if (argc == 2 && argv[1][0] == 'p')
2527 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2531 oldmode = umask((mode_t)0);
2535 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2536 (argv[1][0] == 'c') ? S_IFCHR : 0;
2539 unsigned long majnum, minnum;
2543 majnum = strtoul(argv[2], &c, 0);
2544 if ((c == argv[2]) || (*c != '\0')) {
2545 bi_errorf(Tf_nonnum, "device", "major", argv[2]);
2548 minnum = strtoul(argv[3], &c, 0);
2549 if ((c == argv[3]) || (*c != '\0')) {
2550 bi_errorf(Tf_nonnum, "device", "minor", argv[3]);
2553 dv = makedev(majnum, minnum);
2554 if ((unsigned long)(major(dv)) != majnum) {
2555 bi_errorf(Tf_toolarge, "device", "major", majnum);
2558 if ((unsigned long)(minor(dv)) != minnum) {
2559 bi_errorf(Tf_toolarge, "device", "minor", minnum);
2562 if (mknod(argv[0], mode, dv))
2563 goto c_mknod_failed;
2564 } else if (mkfifo(argv[0], mode)) {
2566 bi_errorf(Tf_sD_s, argv[0], cstrerror(errno));
2575 bi_errorf("usage: mknod [-m mode] name %s", "b|c major minor");
2576 bi_errorf("usage: mknod [-m mode] name %s", "p");
2582 test(1) roughly accepts the following grammar:
2583 oexpr ::= aexpr | aexpr "-o" oexpr ;
2584 aexpr ::= nexpr | nexpr "-a" aexpr ;
2585 nexpr ::= primary | "!" nexpr ;
2586 primary ::= unary-operator operand
2587 | operand binary-operator operand
2592 unary-operator ::= "-a"|"-b"|"-c"|"-d"|"-e"|"-f"|"-G"|"-g"|"-H"|"-h"|
2593 "-k"|"-L"|"-n"|"-O"|"-o"|"-p"|"-r"|"-S"|"-s"|"-t"|
2594 "-u"|"-v"|"-w"|"-x"|"-z";
2596 binary-operator ::= "="|"=="|"!="|"<"|">"|"-eq"|"-ne"|"-gt"|"-ge"|
2597 "-lt"|"-le"|"-ef"|"-nt"|"-ot";
2599 operand ::= <anything>
2602 /* POSIX says > 1 for errors */
2603 #define T_ERR_EXIT 2
2606 c_test(const char **wp)
2608 int argc, rv, invert = 0;
2612 const char *lhs, **swp;
2616 te.getopnd = ptest_getopnd;
2617 te.eval = test_eval;
2618 te.error = ptest_error;
2620 for (argc = 0; wp[argc]; argc++)
2623 if (strcmp(wp[0], Tbracket) == 0) {
2624 if (strcmp(wp[--argc], "]") != 0) {
2625 bi_errorf("missing ]");
2626 return (T_ERR_EXIT);
2631 te.wp_end = wp + argc;
2634 * Attempt to conform to POSIX special cases. This is pretty
2635 * dumb code straight-forward from the 2008 spec, but unlike
2636 * the old pdksh code doesn't live from so many assumptions.
2637 * It does, though, inline some calls to '(*te.funcname)()'.
2648 if (ptest_isa(&te, TM_NOT)) {
2652 if ((op = ptest_isa(&te, TM_UNOP))) {
2654 rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
2656 if (te.flags & TEF_ERROR)
2657 return (T_ERR_EXIT);
2658 return ((invert & 1) ? rv : !rv);
2660 /* let the parser deal with anything else */
2665 /* use inside knowledge of ptest_getopnd inlined below */
2667 if ((op = ptest_isa(&te, TM_BINOP))) {
2668 /* test lhs op rhs */
2669 rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
2672 if (ptest_isa(&te, tm = TM_AND) || ptest_isa(&te, tm = TM_OR)) {
2674 argc = test_eval(&te, TO_STNZE, lhs, NULL, true);
2675 rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, true);
2682 /* back up to lhs */
2684 if (ptest_isa(&te, TM_NOT)) {
2688 if (ptest_isa(&te, TM_OPAREN)) {
2690 /* skip operand, without evaluation */
2692 /* check for closing parenthesis */
2693 op = ptest_isa(&te, TM_CPAREN);
2694 /* back up to operand */
2696 /* if there was a closing paren, handle it */
2699 /* backing up is done before calling the parser */
2701 /* let the parser deal with it */
2704 if (ptest_isa(&te, TM_NOT)) {
2708 if (ptest_isa(&te, TM_OPAREN)) {
2710 /* skip two operands, without evaluation */
2713 /* check for closing parenthesis */
2714 op = ptest_isa(&te, TM_CPAREN);
2715 /* back up to first operand */
2717 /* if there was a closing paren, handle it */
2720 /* backing up is done before calling the parser */
2722 /* defer this to the parser */
2726 /* "The results are unspecified." */
2728 return (test_parse(&te));
2732 * Generic test routines.
2736 test_isop(Test_meta meta, const char *s)
2739 const struct t_op *tbl;
2741 tbl = meta == TM_UNOP ? u_ops : b_ops;
2744 for (; tbl->op_text[0]; tbl++)
2745 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
2746 return (tbl->op_num);
2752 #define test_access(name, mode) access_ex(access, (name), (mode))
2753 #define test_stat(name, buffer) stat_ex((name), (buffer))
2755 #define test_access(name, mode) access((name), (mode))
2756 #define test_stat(name, buffer) stat((name), (buffer))
2760 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
2774 /* Binary operators */
2788 /* consistency check, but does not happen in practice */
2790 te->flags |= TEF_ERROR;
2795 /* for completeness of switch */
2808 return (*opnd1 != '\0');
2812 return (*opnd1 == '\0');
2816 return ((vp = isglobal(opnd1, false)) && (vp->flag & ISSET));
2820 if ((i = *opnd1) == '!' || i == '?')
2822 if ((k = option(opnd1)) == (size_t)-1)
2824 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
2828 /* LINTED use of access */
2829 return (test_access(opnd1, R_OK) == 0);
2833 /* LINTED use of access */
2834 return (test_access(opnd1, W_OK) == 0);
2838 return (ksh_access(opnd1, X_OK) == 0);
2844 return (test_stat(opnd1, &b1) == 0);
2848 return (test_stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
2852 return (stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
2856 return (stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
2860 return (stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
2864 return (stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
2868 #ifdef MKSH__NO_SYMLINK
2871 return (lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
2876 return (stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
2878 /* -H => HP context dependent files (directories) */
2885 * Append a + to filename and check to see if result is
2886 * a setuid directory. CDF stuff in general is hookey,
2887 * since it breaks for, e.g., the following sequence:
2888 * echo hi >foo+; mkdir foo; echo bye >foo/default;
2889 * chmod u+s foo (foo+ refers to the file with hi in it,
2890 * there is no way to get at the file with bye in it;
2891 * please correct me if I'm wrong about this).
2894 nv = shf_smprintf("%s+", opnd1);
2895 i = (stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
2905 return (stat(opnd1, &b1) == 0 &&
2906 (b1.st_mode & S_ISUID) == S_ISUID);
2910 return (stat(opnd1, &b1) == 0 &&
2911 (b1.st_mode & S_ISGID) == S_ISGID);
2916 return (stat(opnd1, &b1) == 0 &&
2917 (b1.st_mode & S_ISVTX) == S_ISVTX);
2924 return (stat(opnd1, &b1) == 0 && (off_t)b1.st_size > (off_t)0);
2928 if (opnd1 && !bi_getn(opnd1, &i)) {
2929 te->flags |= TEF_ERROR;
2932 i = isatty(opnd1 ? i : 0);
2937 return (stat(opnd1, &b1) == 0 && (uid_t)b1.st_uid == ksheuid);
2941 return (stat(opnd1, &b1) == 0 && (gid_t)b1.st_gid == getegid());
2949 if (te->flags & TEF_DBRACKET) {
2950 if ((i = gmatchx(opnd1, opnd2, false)))
2951 record_match(opnd1);
2954 return (strcmp(opnd1, opnd2) == 0);
2958 if (te->flags & TEF_DBRACKET) {
2959 if ((i = gmatchx(opnd1, opnd2, false)))
2960 record_match(opnd1);
2963 return (strcmp(opnd1, opnd2) != 0);
2967 return (strcmp(opnd1, opnd2) < 0);
2971 return (strcmp(opnd1, opnd2) > 0);
2976 * ksh88/ksh93 succeed if file2 can't be stated
2977 * (subtly different from 'does not exist').
2979 return (stat(opnd1, &b1) == 0 &&
2980 (((s = stat(opnd2, &b2)) == 0 &&
2981 b1.st_mtime > b2.st_mtime) || s < 0));
2986 * ksh88/ksh93 succeed if file1 can't be stated
2987 * (subtly different from 'does not exist').
2989 return (stat(opnd2, &b2) == 0 &&
2990 (((s = stat(opnd1, &b1)) == 0 &&
2991 b1.st_mtime < b2.st_mtime) || s < 0));
2995 return (stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0 &&
2996 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
2998 /* all other cases */
3001 /* throw the error */
3016 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
3017 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
3018 /* error already printed.. */
3019 te->flags |= TEF_ERROR;
3041 (*te->error)(te, 0, "internal error: unknown op");
3046 test_parse(Test_env *te)
3050 rv = test_oexpr(te, 1);
3052 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3053 (*te->error)(te, 0, "unexpected operator/operand");
3055 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3059 test_oexpr(Test_env *te, bool do_eval)
3063 if ((rv = test_aexpr(te, do_eval)))
3065 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3066 return (test_oexpr(te, do_eval) || rv);
3071 test_aexpr(Test_env *te, bool do_eval)
3075 if (!(rv = test_nexpr(te, do_eval)))
3077 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3078 return (test_aexpr(te, do_eval) && rv);
3083 test_nexpr(Test_env *te, bool do_eval)
3085 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3086 return (!test_nexpr(te, do_eval));
3087 return (test_primary(te, do_eval));
3091 test_primary(Test_env *te, bool do_eval)
3093 const char *opnd1, *opnd2;
3097 if (te->flags & TEF_ERROR)
3099 if ((*te->isa)(te, TM_OPAREN)) {
3100 rv = test_oexpr(te, do_eval);
3101 if (te->flags & TEF_ERROR)
3103 if (!(*te->isa)(te, TM_CPAREN)) {
3104 (*te->error)(te, 0, "missing )");
3110 * Binary should have precedence over unary in this case
3111 * so that something like test \( -f = -f \) is accepted
3113 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3114 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3115 if ((op = (*te->isa)(te, TM_UNOP))) {
3116 /* unary expression */
3117 opnd1 = (*te->getopnd)(te, op, do_eval);
3119 (*te->error)(te, -1, Tno_args);
3123 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3126 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3128 (*te->error)(te, 0, "expression expected");
3131 if ((op = (*te->isa)(te, TM_BINOP))) {
3132 /* binary expression */
3133 opnd2 = (*te->getopnd)(te, op, do_eval);
3135 (*te->error)(te, -1, "missing second argument");
3139 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3141 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3145 * Plain test (test and [ .. ]) specific routines.
3149 * Test if the current token is a whatever. Accepts the current token if
3150 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3151 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3154 ptest_isa(Test_env *te, Test_meta meta)
3156 /* Order important - indexed by Test_meta values */
3157 static const char * const tokens[] = {
3158 "-o", "-a", "!", "(", ")"
3162 if (te->pos.wp >= te->wp_end)
3163 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3165 if (meta == TM_UNOP || meta == TM_BINOP)
3166 rv = test_isop(meta, *te->pos.wp);
3167 else if (meta == TM_END)
3170 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3171 TO_NONNULL : TO_NONOP;
3173 /* Accept the token? */
3181 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3183 if (te->pos.wp >= te->wp_end)
3184 return (op == TO_FILTT ? "1" : NULL);
3185 return (*te->pos.wp++);
3189 ptest_error(Test_env *te, int ofs, const char *msg)
3193 te->flags |= TEF_ERROR;
3194 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3195 bi_errorf(Tf_sD_s, op, msg);
3197 bi_errorf(Tf_s, msg);
3200 #ifndef MKSH_NO_LIMITS
3204 /* Magic to divine the 'm' and 'v' limits */
3207 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3208 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3209 #define ULIMIT_V_IS_AS
3210 #elif defined(RLIMIT_VMEM)
3211 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3212 #define ULIMIT_V_IS_AS
3214 #define ULIMIT_V_IS_VMEM
3220 #ifdef ULIMIT_V_IS_VMEM
3221 #define ULIMIT_M_IS_RSS
3222 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3223 #define ULIMIT_M_IS_VMEM
3225 #define ULIMIT_M_IS_RSS
3227 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3228 #undef ULIMIT_M_IS_RSS
3232 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3233 #define ULIMIT_V_IS_VMEM
3236 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3237 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3238 #define ULIMIT_M_IS_VMEM
3241 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3242 (RLIMIT_VMEM == RLIMIT_AS)
3243 #undef ULIMIT_M_IS_VMEM
3246 #if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
3247 # error nonsensical m ulimit
3250 #if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
3251 # error nonsensical v ulimit
3255 /* limit resource */
3257 /* multiply by to get rlim_{cur,max} values */
3258 unsigned int factor;
3265 #define RLIMITS_DEFNS
3266 #define FN(lname,lid,lfac,lopt) \
3267 static const struct { \
3269 unsigned int factor; \
3271 char name[sizeof(lname)]; \
3272 } rlimits_ ## lid = { \
3273 lid, lfac, lopt, lname \
3275 #include "rlimits.gen"
3277 static void print_ulimit(const struct limits *, int);
3278 static int set_ulimit(const struct limits *, const char *, int);
3280 static const struct limits * const rlimits[] = {
3281 #define RLIMITS_ITEMS
3282 #include "rlimits.gen"
3285 static const char rlimits_opts[] =
3286 #define RLIMITS_OPTCS
3287 #include "rlimits.gen"
3291 c_ulimit(const char **wp)
3294 int how = SOFT | HARD, optc, what = 'f';
3297 while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
3309 bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
3315 while (i < NELEM(rlimits)) {
3316 if (rlimits[i]->optchar == what)
3320 internal_warningf("ulimit: %c", what);
3323 if (wp[builtin_opt.optind]) {
3324 if (all || wp[builtin_opt.optind + 1]) {
3325 bi_errorf(Ttoo_many_args);
3328 return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
3331 print_ulimit(rlimits[i], how);
3332 else for (i = 0; i < NELEM(rlimits); ++i) {
3333 shprintf("-%c: %-20s ", rlimits[i]->optchar, rlimits[i]->name);
3334 print_ulimit(rlimits[i], how);
3340 set_ulimit(const struct limits *l, const char *v, int how)
3342 rlim_t val = (rlim_t)0;
3343 struct rlimit limit;
3345 if (strcmp(v, "unlimited") == 0)
3346 val = (rlim_t)RLIM_INFINITY;
3350 if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
3353 * Avoid problems caused by typos that evaluate misses due
3354 * to evaluating unset parameters to 0...
3355 * If this causes problems, will have to add parameter to
3356 * evaluate() to control if unset params are 0 or an error.
3358 if (!rval && !ctype(v[0], C_DIGIT)) {
3359 bi_errorf("invalid %s limit: %s", l->name, v);
3362 val = (rlim_t)((rlim_t)rval * l->factor);
3365 if (getrlimit(l->resource, &limit) < 0) {
3367 bi_errorf("limit %s could not be read, contact the mksh developers: %s",
3368 l->name, cstrerror(errno));
3370 /* some can't be read */
3371 limit.rlim_cur = RLIM_INFINITY;
3372 limit.rlim_max = RLIM_INFINITY;
3375 limit.rlim_cur = val;
3377 limit.rlim_max = val;
3378 if (!setrlimit(l->resource, &limit))
3381 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3383 bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
3388 print_ulimit(const struct limits *l, int how)
3390 rlim_t val = (rlim_t)0;
3391 struct rlimit limit;
3393 if (getrlimit(l->resource, &limit)) {
3394 shf_puts("unknown\n", shl_stdout);
3398 val = limit.rlim_cur;
3399 else if (how & HARD)
3400 val = limit.rlim_max;
3401 if (val == (rlim_t)RLIM_INFINITY)
3402 shf_puts("unlimited\n", shl_stdout);
3404 shprintf("%lu\n", (unsigned long)(val / l->factor));
3409 c_rename(const char **wp)
3415 if (wp[0] && !strcmp(wp[0], "--"))
3416 /* skip "--" (options separator) */
3419 /* check for exactly two arguments */
3420 if (wp[0] == NULL /* first argument */ ||
3421 wp[1] == NULL /* second argument */ ||
3422 wp[2] != NULL /* no further args please */)
3424 else if ((rv = rename(wp[0], wp[1])) != 0) {
3426 bi_errorf(Tf_sD_s, "failed", cstrerror(rv));
3433 c_realpath(const char **wp)
3440 if (wp[0] && !strcmp(wp[0], "--"))
3441 /* skip "--" (options separator) */
3444 /* check for exactly one argument */
3445 if (wp[0] == NULL || wp[1] != NULL)
3447 else if ((buf = do_realpath(wp[0])) == NULL) {
3449 bi_errorf(Tf_sD_s, wp[0], cstrerror(rv));
3450 if ((unsigned int)rv > 255)
3453 shprintf(Tf_sN, buf);
3462 c_cat(const char **wp)
3464 int fd = STDIN_FILENO, rv;
3466 const char *fn = "<stdin>";
3469 #define MKSH_CAT_BUFSIZ 4096
3471 /* parse options: POSIX demands we support "-u" as no-op */
3472 while ((rv = ksh_getopt(wp, &builtin_opt, "u")) != -1) {
3475 /* we already operate unbuffered */
3482 wp += builtin_opt.optind;
3485 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3486 bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
3491 opipe = block_pipe();
3498 else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
3499 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3504 while (/* CONSTCOND */ 1) {
3505 if ((n = blocking_read(fd, (cp = buf),
3506 MKSH_CAT_BUFSIZ)) == -1) {
3507 if (errno == EINTR) {
3510 /* give the user a chance to ^C out */
3512 /* interrupted, try again */
3513 opipe = block_pipe();
3516 /* an error occured during reading */
3517 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3521 /* end of file reached */
3526 if ((w = write(STDOUT_FILENO, cp, n)) != -1) {
3531 if (errno == EINTR) {
3535 /* give the user a chance to ^C out */
3537 /* interrupted, try again */
3538 opipe = block_pipe();
3541 if (errno == EPIPE) {
3542 /* fake receiving signal */
3543 rv = ksh_sigmask(SIGPIPE);
3545 /* an error occured during writing */
3546 bi_errorf(Tf_sD_s, "<stdout>",
3550 if (fd != STDIN_FILENO)
3555 if (fd != STDIN_FILENO)
3568 c_sleep(const char **wp)
3575 if (wp[0] && !strcmp(wp[0], "--"))
3576 /* skip "--" (options separator) */
3579 if (!wp[0] || wp[1])
3581 else if (parse_usec(wp[0], &tv))
3582 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno), wp[0]);
3584 #ifndef MKSH_NOPROSPECTOFWORK
3585 sigset_t omask, bmask;
3587 /* block a number of signals from interrupting us, though */
3588 (void)sigemptyset(&bmask);
3589 (void)sigaddset(&bmask, SIGPIPE);
3590 (void)sigaddset(&bmask, SIGCHLD);
3592 (void)sigaddset(&bmask, SIGWINCH);
3595 (void)sigaddset(&bmask, SIGINFO);
3598 (void)sigaddset(&bmask, SIGUSR1);
3601 (void)sigaddset(&bmask, SIGUSR2);
3603 sigprocmask(SIG_BLOCK, &bmask, &omask);
3605 if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3607 * strictly speaking only for SIGALRM, but the
3608 * execution may be interrupted by other signals
3612 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
3613 #ifndef MKSH_NOPROSPECTOFWORK
3614 /* this will re-schedule signal delivery */
3615 sigprocmask(SIG_SETMASK, &omask, NULL);
3622 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
3624 c_suspend(const char **wp)
3626 if (wp[1] != NULL) {
3627 bi_errorf(Ttoo_many_args);
3631 /* Can't suspend an orphaned process group. */
3632 if (getpgid(kshppid) == getpgid(0) ||
3633 getsid(kshppid) != getsid(0)) {
3634 bi_errorf("can't suspend a login shell");