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.340 2017/04/12 17:46:29 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 Unicode */
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();
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)
755 if (!ksh_isalias(*cp))
763 c_alias(const char **wp)
765 struct table *t = &aliases;
766 int rv = 0, prefix = 0;
767 bool rflag = false, tflag, Uflag = false, pflag = false;
771 builtin_opt.flags |= GF_PLUSOPT;
772 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
773 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
777 t = NULL; /* fix "alias -dt" */
793 * kludge for tracked alias initialization
794 * (don't do a path search, just make an entry)
809 wp += builtin_opt.optind;
811 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
812 (wp[0][0] == '-' || wp[0][0] == '+') && wp[0][1] == '\0') {
817 tflag = t == &taliases;
819 /* "hash -r" means reset all the tracked aliases.. */
821 static const char *args[] = {
822 Tunalias, "-ta", NULL
826 shprintf("%s: -r flag can only be used with -t"
827 " and without arguments\n", Talias);
830 ksh_getopt_reset(&builtin_opt, GF_ERROR);
831 return (c_unalias(args));
837 for (p = ktsort(t); (ap = *p++) != NULL; )
838 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
840 shprintf(Tf_s_, Talias);
841 shf_puts(ap->name, shl_stdout);
843 shf_putc('=', shl_stdout);
844 print_value_quoted(shl_stdout, ap->val.s);
846 shf_putc('\n', shl_stdout);
850 for (; *wp != NULL; wp++) {
851 const char *alias = *wp, *val, *newval;
856 if ((val = cstrchr(alias, '='))) {
857 strndupx(xalias, alias, val++ - alias, ATEMP);
860 if (!valid_alias_name(alias) || *alias == '-') {
861 bi_errorf(Tinvname, alias, Talias);
862 afree(xalias, ATEMP);
866 if (val == NULL && !tflag && !xflag) {
867 ap = ktsearch(t, alias, h);
868 if (ap != NULL && (ap->flag&ISSET)) {
870 shprintf(Tf_s_, Talias);
871 shf_puts(ap->name, shl_stdout);
873 shf_putc('=', shl_stdout);
874 print_value_quoted(shl_stdout, ap->val.s);
876 shf_putc('\n', shl_stdout);
878 shprintf(Tf_s_s_sN, alias, Talias, Tnot_found);
883 ap = ktenter(t, alias, h);
884 ap->type = tflag ? CTALIAS : CALIAS;
885 /* Are we setting the value or just some flags? */
886 if ((val && !tflag) || (!val && tflag && !Uflag)) {
887 if (ap->flag&ALLOC) {
888 ap->flag &= ~(ALLOC|ISSET);
889 afree(ap->val.s, APERM);
891 /* ignore values for -t (AT&T ksh does this) */
893 search_path(alias, path, X_OK, NULL) :
896 strdupx(ap->val.s, newval, APERM);
897 ap->flag |= ALLOC|ISSET;
906 afree(xalias, ATEMP);
913 c_unalias(const char **wp)
915 struct table *t = &aliases;
920 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
927 /* fix "unalias -dt" */
943 wp += builtin_opt.optind;
945 for (; *wp != NULL; wp++) {
946 ap = ktsearch(t, *wp, hash(*wp));
952 if (ap->flag&ALLOC) {
953 ap->flag &= ~(ALLOC|ISSET);
954 afree(ap->val.s, APERM);
956 ap->flag &= ~(DEFINED|ISSET|EXPORT);
962 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
963 if (ap->flag&ALLOC) {
964 ap->flag &= ~(ALLOC|ISSET);
965 afree(ap->val.s, APERM);
967 ap->flag &= ~(DEFINED|ISSET|EXPORT);
975 c_let(const char **wp)
981 /* AT&T ksh does this */
984 for (wp++; *wp; wp++)
985 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
986 /* distinguish error from zero result */
995 c_jobs(const char **wp)
997 int optc, flag = 0, nflag = 0, rv = 0;
999 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1011 /* debugging: print zombies */
1017 wp += builtin_opt.optind;
1019 if (j_jobs(NULL, flag, nflag))
1023 if (j_jobs(*wp, flag, nflag))
1029 #ifndef MKSH_UNEMPLOYED
1031 c_fgbg(const char **wp)
1033 bool bg = strcmp(*wp, Tbg) == 0;
1036 if (!Flag(FMONITOR)) {
1037 bi_errorf("job control not enabled");
1040 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1042 wp += builtin_opt.optind;
1045 rv = j_resume(*wp, bg);
1047 rv = j_resume("%%", bg);
1048 /* fg returns $? of the job unless POSIX */
1049 return ((bg | Flag(FPOSIX)) ? 0 : rv);
1053 /* format a single kill item */
1055 kill_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1057 const struct kill_info *ki = (const struct kill_info *)arg;
1060 shf_snprintf(buf, buflen, "%*u %*s %s",
1062 ki->name_width, sigtraps[i].name,
1067 c_kill(const char **wp)
1074 /* assume old style options if -digits or -UPPERCASE */
1075 if ((p = wp[1]) && *p == '-' && (ksh_isdigit(p[1]) ||
1076 ksh_isupper(p[1]))) {
1077 if (!(t = gettrap(p + 1, false, false))) {
1078 bi_errorf(Tbad_sig_s, p + 1);
1081 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1085 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1091 if (!(t = gettrap(builtin_opt.optarg,
1093 bi_errorf(Tbad_sig_s,
1094 builtin_opt.optarg);
1101 i = builtin_opt.optind;
1103 if ((lflag && t) || (!wp[i] && !lflag)) {
1105 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1106 " { job | pid | pgrp } ...\n"
1107 "\tkill -l [exit_status ...]\n", shl_out);
1115 for (; wp[i]; i++) {
1116 if (!bi_getn(wp[i], &n))
1118 #if (ksh_NSIG <= 128)
1119 if (n > 128 && n < 128 + ksh_NSIG)
1122 if (n > 0 && n < ksh_NSIG)
1123 shprintf(Tf_sN, sigtraps[n].name);
1127 } else if (Flag(FPOSIX)) {
1129 while (n < ksh_NSIG) {
1130 shf_puts(sigtraps[n].name, shl_stdout);
1131 shf_putc(++n == ksh_NSIG ? '\n' : ' ',
1135 ssize_t w, mess_cols = 0, mess_octs = 0;
1136 int j = ksh_NSIG - 1;
1137 struct kill_info ki = { 0, 0 };
1138 struct columnise_opts co;
1142 } while ((j /= 10));
1144 for (j = 1; j < ksh_NSIG; j++) {
1145 w = strlen(sigtraps[j].name);
1146 if (w > ki.name_width)
1148 w = strlen(sigtraps[j].mess);
1151 w = utf_mbswidth(sigtraps[j].mess);
1156 co.shf = shl_stdout;
1158 co.prefcol = co.do_last = true;
1160 print_columns(&co, (unsigned int)(ksh_NSIG - 1),
1161 kill_fmt_entry, (void *)&ki,
1162 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1163 ki.num_width + 1 + ki.name_width + 1 + mess_cols);
1168 sig = t ? t->signal : SIGTERM;
1169 for (; (p = wp[i]); i++) {
1173 } else if (!getn(p, &n)) {
1174 bi_errorf(Tf_sD_s, p,
1175 "arguments must be jobs or process IDs");
1178 if (mksh_kill(n, sig) < 0) {
1179 bi_errorf(Tf_sD_s, p, cstrerror(errno));
1188 getopts_reset(int val)
1191 ksh_getopt_reset(&user_opt, GF_NONAME |
1192 (Flag(FPOSIX) ? 0 : GF_PLUSOPT));
1193 user_opt.optind = user_opt.uoptind = val;
1198 c_getopts(const char **wp)
1201 const char *opts, *var;
1203 struct tbl *vq, *voptarg;
1205 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1207 wp += builtin_opt.optind;
1211 bi_errorf(Tf_sD_s, "options", Tno_args);
1217 bi_errorf(Tf_sD_s, Tname, Tno_args);
1220 if (!*var || *skip_varname(var, true)) {
1221 bi_errorf(Tf_sD_s, var, Tnot_ident);
1225 if (e->loc->next == NULL) {
1226 internal_warningf(Tf_sD_s, Tgetopts, Tno_args);
1229 /* Which arguments are we parsing... */
1231 wp = e->loc->next->argv;
1233 *--wp = e->loc->next->argv[0];
1235 /* Check that our saved state won't cause a core dump... */
1236 for (argc = 0; wp[argc]; argc++)
1238 if (user_opt.optind > argc ||
1240 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1241 bi_errorf("arguments changed since last call");
1245 user_opt.optarg = NULL;
1246 optc = ksh_getopt(wp, &user_opt, opts);
1248 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1254 * POSIX says var is set to ? at end-of-options, AT&T ksh
1255 * sets it to null - we go with POSIX...
1257 buf[0] = optc < 0 ? '?' : optc;
1261 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1262 user_opt.uoptind = user_opt.optind;
1264 voptarg = global("OPTARG");
1265 /* AT&T ksh clears ro and int */
1266 voptarg->flag &= ~RDONLY;
1267 /* Paranoia: ensure no bizarre results. */
1268 if (voptarg->flag & INTEGER)
1269 typeset("OPTARG", 0, INTEGER, 0, 0);
1270 if (user_opt.optarg == NULL)
1273 /* this can't fail (haing cleared readonly/integer) */
1274 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1279 /* Error message already printed (integer, readonly) */
1280 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1283 typeset(var, EXPORT, 0, 0, 0);
1285 return (optc < 0 ? 1 : rv);
1288 #ifndef MKSH_NO_CMDLINE_EDITING
1290 c_bind(const char **wp)
1300 while ((optc = ksh_getopt(wp, &builtin_opt,
1319 wp += builtin_opt.optind;
1323 rv = x_bind(NULL, NULL,
1329 for (; *wp != NULL; wp++) {
1330 if ((cp = cstrchr(*wp, '=')) == NULL)
1333 strdupx(up, *wp, ATEMP);
1334 up[cp++ - *wp] = '\0';
1336 if (x_bind(up ? up : *wp, cp,
1350 c_shift(const char **wp)
1352 struct block *l = e->loc;
1357 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1359 arg = wp[builtin_opt.optind];
1363 else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
1364 /* error already printed */
1367 } else if (!(n = val)) {
1371 bi_errorf(Tf_sD_s, Tbadnum, arg);
1375 bi_errorf("nothing to shift");
1378 l->argv[n] = l->argv[0];
1385 c_umask(const char **wp)
1389 bool symbolic = false;
1392 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1400 cp = wp[builtin_opt.optind];
1402 old_umask = umask((mode_t)0);
1408 old_umask = ~old_umask;
1410 for (i = 0; i < 3; i++) {
1413 for (j = 0; j < 3; j++)
1414 if (old_umask & (1 << (8 - (3*i + j))))
1419 shprintf(Tf_sN, buf);
1421 shprintf("%#3.3o\n", (unsigned int)old_umask);
1425 if (ksh_isdigit(*cp)) {
1427 while (*cp >= ord('0') && *cp <= ord('7')) {
1428 new_umask = new_umask * 8 + ksh_numdig(*cp);
1436 /* symbolic format */
1437 int positions, new_val;
1440 old_umask = umask((mode_t)0);
1441 /* in case of error */
1443 old_umask = ~old_umask;
1444 new_umask = old_umask;
1447 while (*cp && vstrchr(Taugo, *cp))
1465 if (!vstrchr("=+-", op = *cp))
1469 while (*cp && vstrchr("rwxugoXs", *cp))
1471 case 'r': new_val |= 04; break;
1472 case 'w': new_val |= 02; break;
1473 case 'x': new_val |= 01; break;
1475 new_val |= old_umask >> 6;
1478 new_val |= old_umask >> 3;
1481 new_val |= old_umask >> 0;
1484 if (old_umask & 0111)
1491 new_val = (new_val & 07) * positions;
1494 new_umask &= ~new_val;
1497 new_umask = new_val |
1498 (new_umask & ~(positions * 07));
1501 new_umask |= new_val;
1506 } else if (!vstrchr("=+-", *cp))
1510 bi_errorf("bad mask");
1513 new_umask = ~new_umask;
1521 c_dot(const char **wp)
1523 const char *file, *cp, **argv;
1524 int argc, rv, errcode;
1526 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1529 if ((cp = wp[builtin_opt.optind]) == NULL) {
1530 bi_errorf(Tno_args);
1533 file = search_path(cp, path, R_OK, &errcode);
1534 if (!file && errcode == ENOENT && wp[0][0] == 's' &&
1535 search_access(cp, R_OK) == 0)
1538 bi_errorf(Tf_sD_s, cp, cstrerror(errcode));
1542 /* Set positional parameters? */
1543 if (wp[builtin_opt.optind + 1]) {
1544 argv = wp + builtin_opt.optind;
1546 argv[0] = e->loc->argv[0];
1547 for (argc = 0; argv[argc + 1]; argc++)
1553 /* SUSv4: OR with a high value never written otherwise */
1555 if ((rv = include(file, argc, argv, false)) < 0) {
1556 /* should not happen */
1557 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
1560 if (exstat & 0x4000)
1561 /* detect old exstat, use 0 in that case */
1567 c_wait(const char **wp)
1571 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1573 wp += builtin_opt.optind;
1575 while (waitfor(NULL, &sig) >= 0)
1580 rv = waitfor(*wp, &sig);
1582 /* magic exit code: bad job-id */
1583 rv = sig ? sig : 127;
1588 static char REPLY[] = "REPLY";
1590 c_read(const char **wp)
1592 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1593 int c, fd = 0, rv = 0;
1594 bool savehist = false, intoarray = false, aschars = false;
1595 bool rawmode = false, expanding = false;
1596 bool lastparmmode = false, lastparmused = false;
1597 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1599 size_t bytesleft = 128, bytesread;
1600 struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
1601 char *cp, *allocd = NULL, *xp;
1606 bool restore_tios = false;
1607 /* to catch read -aN2 foo[i] */
1608 bool subarray = false;
1610 bool hastimeout = false;
1611 struct timeval tv, tvlim;
1612 #define c_read_opts "Aad:N:n:prst:u,"
1614 #define c_read_opts "Aad:N:n:prsu,"
1616 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1621 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1630 delim = builtin_opt.optarg[0];
1634 readmode = c == 'N' ? BYTES : UPTO;
1635 if (!bi_getn(builtin_opt.optarg, &c))
1638 readmode = readmode == BYTES ? READALL : UPTO;
1641 bytesleft = (unsigned int)c;
1644 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1645 bi_errorf(Tf_coproc, ccp);
1657 if (parse_usec(builtin_opt.optarg, &tv)) {
1658 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno),
1659 builtin_opt.optarg);
1666 if (!builtin_opt.optarg[0])
1668 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1669 bi_errorf(Tf_sD_sD_s, "-u", builtin_opt.optarg, ccp);
1676 wp += builtin_opt.optind;
1680 if (intoarray && wp[1] != NULL) {
1681 bi_errorf(Ttoo_many_args);
1685 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1686 strdupx(allocd, *wp, ATEMP);
1687 allocd[ccp - *wp] = '\0';
1691 * AT&T ksh says it prints prompt on fd if it's open
1692 * for writing and is a tty, but it doesn't do it
1693 * (it also doesn't check the interactive flag,
1694 * as is indicated in the Korn Shell book).
1696 shf_puts(ccp + 1, shl_out);
1701 Xinit(xs, xp, bytesleft, ATEMP);
1703 if (readmode == LINES)
1705 else if (isatty(fd)) {
1706 x_mkraw(fd, &tios, true);
1707 restore_tios = true;
1713 timeradd(&tvlim, &tv, &tvlim);
1723 FD_SET((unsigned int)fd, &fdset);
1725 timersub(&tvlim, &tv, &tv);
1726 if (tv.tv_sec < 0) {
1727 /* timeout expired globally */
1732 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
1736 /* timeout expired for this call */
1739 goto c_read_readdone;
1741 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
1748 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1749 saved_mode = setmode(fd, O_TEXT);
1751 if ((bytesread = blocking_read(fd, xp, bytesleft)) == (size_t)-1) {
1752 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1753 saved_errno = errno;
1754 setmode(fd, saved_mode);
1755 errno = saved_errno;
1757 if (errno == EINTR) {
1758 /* check whether the signal would normally kill */
1759 if (!fatal_trap_check()) {
1760 /* no, just ignore the signal */
1761 goto c_read_readloop;
1763 /* pretend the read was killed */
1765 /* unexpected error */
1766 bi_errorf(Tf_s, cstrerror(errno));
1771 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1772 setmode(fd, saved_mode);
1777 if (bytesread == 0) {
1778 /* end of file reached */
1780 goto c_read_readdone;
1783 XcheckN(xs, xp, bytesleft);
1788 /* end of file reached */
1791 goto c_read_readdone;
1794 if (bytesread == 0) {
1795 /* end of file reached */
1797 /* may be partial read: $? = 1, but content */
1798 goto c_read_readdone;
1801 if ((bytesleft -= bytesread) == 0)
1802 goto c_read_readdone;
1805 if (bytesread == 0) {
1806 /* end of file reached */
1808 goto c_read_readdone;
1810 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
1811 /* skip any read NULs unless delimiter */
1817 if (Flag(FTALKING_I) && isatty(fd)) {
1819 * set prompt in case this is
1820 * called from .profile or $ENV
1822 set_prompt(PS2, NULL);
1825 /* drop the backslash */
1827 /* and the delimiter */
1830 } else if (c == delim) {
1831 goto c_read_readdone;
1832 } else if (!rawmode && c == '\\') {
1839 goto c_read_readloop;
1842 bytesread = Xlength(xs, xp);
1846 * state: we finished reading the input and NUL terminated it
1847 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
1848 * rv = 3 if timeout, 1 if EOF, 0 otherwise (errors handled already)
1852 /* clean up coprocess if needed, on EOF/error/timeout */
1853 coproc_read_close(fd);
1854 if (readmode == READALL && (rv == 1 || (rv == 3 && bytesread)))
1855 /* EOF is no error here */
1860 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
1862 ccp = cp = Xclose(xs, xp);
1864 XinitN(xs, 128, ATEMP);
1867 subarray = last_lookup_was_array;
1868 if (vp->flag & RDONLY) {
1870 bi_errorf(Tf_ro, *wp);
1876 /* counter for array index */
1877 c = subarray ? arrayindex(vp) : 0;
1878 /* exporting an array is currently pointless */
1879 unset(vp, subarray ? 0 : 1);
1882 /* skip initial IFS whitespace */
1883 while (bytesread && is_ifsws(*ccp)) {
1887 /* trim trailing IFS whitespace */
1888 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
1893 xp = Xstring(xs, xp);
1894 /* generate next word */
1898 goto c_read_splitdone;
1899 /* zero out next parameters */
1900 goto c_read_gotword;
1905 bytesleft = utf_ptradj(ccp);
1906 while (bytesleft && bytesread) {
1911 if (xp[-1] == '\0') {
1915 goto c_read_gotword;
1918 if (!intoarray && wp[1] == NULL)
1919 lastparmmode = true;
1922 /* copy until IFS character */
1929 goto c_read_splitcopy;
1930 } else if (ctype(ch, C_IFS)) {
1932 } else if (!rawmode && ch == '\\') {
1942 xsave = Xsavepos(xs, xp);
1943 /* copy word delimiter: IFSWS+IFS,IFSWS */
1949 if (!ctype(ch, C_IFS))
1951 if (lastparmmode && !expanding && !rawmode && ch == '\\') {
1961 if (!ctype(ch, C_IFSWS))
1964 while (bytesread && is_ifsws(*ccp)) {
1970 /* if no more parameters, rinse and repeat */
1971 if (lastparmmode && bytesread) {
1972 lastparmused = true;
1973 goto c_read_splitlast;
1975 /* get rid of the delimiter unless we pack the rest */
1977 xp = Xrestpos(xs, xp, xsave);
1982 /* array element passed, accept first read */
1984 bi_errorf("nested arrays not yet supported");
1985 goto c_read_spliterr;
1992 vq = arraysearch(vp, c++);
1995 /* must be checked before exporting */
1996 if (vq->flag & RDONLY)
1997 goto c_read_splitro;
1999 typeset(*wp, EXPORT, 0, 0, 0);
2001 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
2002 goto c_read_spliterr;
2004 setint_v(vq, vq, false);
2005 /* protect from UTFMODE changes */
2008 if (intoarray || *++wp != NULL)
2009 goto c_read_splitloop;
2016 afree(allocd, ATEMP);
2019 mksh_tcset(fd, &tios);
2020 return (rv == 3 ? ksh_sigmask(SIGALRM) : rv);
2025 c_eval(const char **wp)
2027 struct source *s, *saves = source;
2028 unsigned char savef;
2031 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2033 s = pushs(SWORDS, ATEMP);
2034 s->u.strv = wp + builtin_opt.optind;
2035 s->line = current_lineno;
2038 * The following code handles the case where the command is
2039 * empty due to failed command substitution, for example by
2041 * This has historically returned 1 by AT&T ksh88. In this
2042 * case, shell() will not set or change exstat because the
2043 * compiled tree is empty, so it will use the value we pass
2044 * from subst_exstat, which is cleared in execute(), so it
2045 * should have been 0 if there were no substitutions.
2047 * POSIX however says we don't do this, even though it is
2048 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2049 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2051 * 2.9.1: Simple Commands
2052 * ... If there is a command name, execution shall
2053 * continue as described in 2.9.1.1 [Command Search
2054 * and Execution]. If there is no command name, but
2055 * the command contained a command substitution, the
2056 * command shall complete with the exit status of the
2057 * last command substitution performed.
2058 * 2.9.1.1: Command Search and Execution
2059 * (1) a. If the command name matches the name of a
2060 * special built-in utility, that special built-in
2061 * utility shall be invoked.
2063 * If there are no arguments, or only null arguments,
2064 * eval shall return a zero exit status; ...
2066 /* AT&T ksh88: use subst_exstat */
2067 /* exstat = subst_exstat; */
2068 /* SUSv4: OR with a high value never written otherwise */
2071 savef = Flag(FERREXIT);
2072 Flag(FERREXIT) |= 0x80;
2074 Flag(FERREXIT) = savef;
2077 if (exstat & 0x4000)
2078 /* detect old exstat, use 0 in that case */
2084 c_trap(const char **wp)
2090 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2092 wp += builtin_opt.optind;
2097 shf_puts("trap -- ", shl_stdout);
2098 print_value_quoted(shl_stdout, p->trap);
2099 shprintf(Tf__sN, p->name);
2106 if (getn(*wp, &i)) {
2107 /* first argument is a signal number, reset them all */
2110 /* first argument must be a command, then */
2117 /* set/clear the traps */
2120 if (!(p = gettrap(*wp++, true, true))) {
2121 warningf(true, Tbad_sig_ss, builtin_argv0, wp[-1]);
2129 c_exitreturn(const char **wp)
2135 goto c_exitreturn_err;
2136 exstat = bi_getn(wp[1], &n) ? (n & 0xFF) : 1;
2137 } else if (trap_exstat != -1)
2138 exstat = trap_exstat;
2140 if (wp[0][0] == 'r') {
2145 * need to tell if this is exit or return so trap exit will
2146 * work right (POSIX)
2148 for (ep = e; ep; ep = ep->oenv)
2149 if (STOP_RETURN(ep->type)) {
2155 if (how == LEXIT && !really_exit && j_stopped_running()) {
2160 /* get rid of any I/O redirections */
2166 bi_errorf(Ttoo_many_args);
2171 c_brkcont(const char **wp)
2175 struct env *ep, *last_ep = NULL;
2178 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2180 arg = wp[builtin_opt.optind];
2184 else if (!bi_getn(arg, &n))
2187 /* AT&T ksh does this for non-interactive shells only - weird */
2188 bi_errorf("%s: bad value", arg);
2191 quit = (unsigned int)n;
2193 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2194 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2195 if (ep->type == E_LOOP) {
2198 ep->flags |= EF_BRKCONT_PASS;
2204 * AT&T ksh doesn't print a message - just does what it
2205 * can. We print a message 'cause it helps in debugging
2206 * scripts, but don't generate an error (ie, keep going).
2208 if ((unsigned int)n == quit) {
2209 warningf(true, Tf_cant_s, wp[0], wp[0]);
2213 * POSIX says if n is too big, the last enclosing loop
2214 * shall be used. Doesn't say to print an error but we
2215 * do anyway 'cause the user messed up.
2218 last_ep->flags &= ~EF_BRKCONT_PASS;
2219 warningf(true, "%s: can only %s %u level(s)",
2220 wp[0], wp[0], (unsigned int)n - quit);
2223 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2231 c_set(const char **wp)
2235 struct block *l = e->loc;
2238 if (wp[1] == NULL) {
2239 static const char *args[] = { Tset, "-", NULL };
2240 return (c_typeset(args));
2243 if ((argi = parse_args(wp, OF_SET, &setargs)) < 0)
2251 while (*++wp != NULL)
2252 strdupx(*wp, *wp, &l->area);
2253 l->argc = wp - owp - 1;
2254 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2255 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2259 * POSIX says set exit status is 0, but old scripts that use
2260 * getopt(1) use the construct
2261 * set -- $(getopt ab:c "$@")
2262 * which assumes the exit value set will be that of the $()
2263 * (subst_exstat is cleared in execute() so that it will be 0
2264 * if there are no command substitutions).
2266 #ifdef MKSH_LEGACY_MODE
2267 /* traditional behaviour, unless set -o posix */
2268 return (Flag(FPOSIX) ? 0 : subst_exstat);
2270 /* conformant behaviour, unless set -o sh +o posix */
2271 return (Flag(FSH) && !Flag(FPOSIX) ? subst_exstat : 0);
2276 c_unset(const char **wp)
2280 bool unset_var = true;
2282 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2291 /*XXX not reached due to GF_ERROR */
2294 wp += builtin_opt.optind;
2295 for (; (id = *wp) != NULL; wp++)
2297 /* unset variable */
2303 if (n > 3 && id[n-3] == '[' && id[n-2] == '*' &&
2305 strndupx(cp, id, n - 3, ATEMP);
2309 optc = vstrchr(id, '[') ? 0 : 1;
2314 if ((vp->flag&RDONLY)) {
2315 warningf(true, Tf_ro, vp->name);
2320 /* unset function */
2326 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2327 const char *prefix, const char *suffix)
2331 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2332 tv_sec, tv_usec, suffix);
2334 shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
2335 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2339 c_times(const char **wp MKSH_A_UNUSED)
2341 struct rusage usage;
2343 getrusage(RUSAGE_SELF, &usage);
2344 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2345 usage.ru_utime.tv_usec, 0, null, T1space);
2346 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2347 usage.ru_stime.tv_usec, 0, null, "\n");
2349 getrusage(RUSAGE_CHILDREN, &usage);
2350 p_time(shl_stdout, false, usage.ru_utime.tv_sec,
2351 usage.ru_utime.tv_usec, 0, null, T1space);
2352 p_time(shl_stdout, false, usage.ru_stime.tv_sec,
2353 usage.ru_stime.tv_usec, 0, null, "\n");
2359 * time pipeline (really a statement, not a built-in command)
2362 timex(struct op *t, int f, volatile int *xerrok)
2364 #define TF_NOARGS BIT(0)
2365 #define TF_NOREAL BIT(1) /* don't report real time */
2366 #define TF_POSIX BIT(2) /* report in POSIX format */
2368 struct rusage ru0, ru1, cru0, cru1;
2369 struct timeval usrtime, systime, tv0, tv1;
2372 getrusage(RUSAGE_SELF, &ru0);
2373 getrusage(RUSAGE_CHILDREN, &cru0);
2376 * Two ways of getting cpu usage of a command: just use t0
2377 * and t1 (which will get cpu usage from other jobs that
2378 * finish while we are executing t->left), or get the
2379 * cpu usage of t->left. AT&T ksh does the former, while
2380 * pdksh tries to do the later (the j_usrtime hack doesn't
2381 * really work as it only counts the last job).
2383 timerclear(&j_usrtime);
2384 timerclear(&j_systime);
2385 rv = execute(t->left, f | XTIME, xerrok);
2386 if (t->left->type == TCOM)
2387 tf |= t->left->str[0];
2389 getrusage(RUSAGE_SELF, &ru1);
2390 getrusage(RUSAGE_CHILDREN, &cru1);
2394 if (tf & TF_NOARGS) {
2395 /* ksh93 - report shell times (shell+kids) */
2397 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2398 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2400 timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
2401 timeradd(&usrtime, &j_usrtime, &usrtime);
2402 timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
2403 timeradd(&systime, &j_systime, &systime);
2406 if (!(tf & TF_NOREAL)) {
2407 timersub(&tv1, &tv0, &tv1);
2409 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2410 5, Treal_sp1, "\n");
2412 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2413 5, null, Treal_sp2);
2416 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2417 5, Tuser_sp1, "\n");
2419 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2420 5, null, Tuser_sp2);
2422 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2425 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2426 5, null, " system\n");
2433 timex_hook(struct op *t, char **volatile *app)
2439 ksh_getopt_reset(&opt, 0);
2440 /* start at the start */
2442 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2445 t->str[0] |= TF_POSIX;
2448 errorf(Tf_optfoo, Ttime, Tcolsp,
2449 opt.optarg[0], Tunknown_option);
2451 errorf(Tf_optfoo, Ttime, Tcolsp,
2452 opt.optarg[0], Treq_arg);
2454 /* Copy command words down over options. */
2455 if (opt.optind != 0) {
2456 for (i = 0; i < opt.optind; i++)
2457 afree(wp[i], ATEMP);
2458 for (i = 0, j = opt.optind; (wp[i] = wp[j]); i++, j++)
2462 t->str[0] |= TF_NOARGS;
2466 /* exec with no args - args case is taken care of in comexec() */
2468 c_exec(const char **wp MKSH_A_UNUSED)
2472 /* make sure redirects stay in place */
2473 if (e->savefd != NULL) {
2474 for (i = 0; i < NUFILE; i++) {
2475 if (e->savefd[i] > 0)
2476 close(e->savefd[i]);
2478 * keep all file descriptors > 2 private for ksh,
2479 * but not for POSIX or legacy/kludge sh
2481 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2483 fcntl(i, F_SETFD, FD_CLOEXEC);
2490 #if HAVE_MKNOD && !defined(__OS2__)
2492 c_mknod(const char **wp)
2494 int argc, optc, rv = 0;
2495 bool ismkfifo = false;
2498 mode_t mode = 0, oldmode = 0;
2500 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2503 set = setmode(builtin_opt.optarg);
2505 bi_errorf("invalid file mode");
2508 mode = getmode(set, (mode_t)(DEFFILEMODE));
2509 free_ossetmode(set);
2515 argv = &wp[builtin_opt.optind];
2516 if (argv[0] == NULL)
2518 for (argc = 0; argv[argc]; argc++)
2520 if (argc == 2 && argv[1][0] == 'p')
2522 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2526 oldmode = umask((mode_t)0);
2530 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2531 (argv[1][0] == 'c') ? S_IFCHR : 0;
2534 unsigned long majnum, minnum;
2538 majnum = strtoul(argv[2], &c, 0);
2539 if ((c == argv[2]) || (*c != '\0')) {
2540 bi_errorf(Tf_nonnum, "device", "major", argv[2]);
2543 minnum = strtoul(argv[3], &c, 0);
2544 if ((c == argv[3]) || (*c != '\0')) {
2545 bi_errorf(Tf_nonnum, "device", "minor", argv[3]);
2548 dv = makedev(majnum, minnum);
2549 if ((unsigned long)(major(dv)) != majnum) {
2550 bi_errorf(Tf_toolarge, "device", "major", majnum);
2553 if ((unsigned long)(minor(dv)) != minnum) {
2554 bi_errorf(Tf_toolarge, "device", "minor", minnum);
2557 if (mknod(argv[0], mode, dv))
2558 goto c_mknod_failed;
2559 } else if (mkfifo(argv[0], mode)) {
2561 bi_errorf(Tf_sD_s, argv[0], cstrerror(errno));
2570 bi_errorf("usage: mknod [-m mode] name %s", "b|c major minor");
2571 bi_errorf("usage: mknod [-m mode] name %s", "p");
2577 test(1) roughly accepts the following grammar:
2578 oexpr ::= aexpr | aexpr "-o" oexpr ;
2579 aexpr ::= nexpr | nexpr "-a" aexpr ;
2580 nexpr ::= primary | "!" nexpr ;
2581 primary ::= unary-operator operand
2582 | operand binary-operator operand
2587 unary-operator ::= "-a"|"-b"|"-c"|"-d"|"-e"|"-f"|"-G"|"-g"|"-H"|"-h"|
2588 "-k"|"-L"|"-n"|"-O"|"-o"|"-p"|"-r"|"-S"|"-s"|"-t"|
2589 "-u"|"-v"|"-w"|"-x"|"-z";
2591 binary-operator ::= "="|"=="|"!="|"<"|">"|"-eq"|"-ne"|"-gt"|"-ge"|
2592 "-lt"|"-le"|"-ef"|"-nt"|"-ot";
2594 operand ::= <anything>
2597 /* POSIX says > 1 for errors */
2598 #define T_ERR_EXIT 2
2601 c_test(const char **wp)
2603 int argc, rv, invert = 0;
2607 const char *lhs, **swp;
2611 te.getopnd = ptest_getopnd;
2612 te.eval = test_eval;
2613 te.error = ptest_error;
2615 for (argc = 0; wp[argc]; argc++)
2618 if (strcmp(wp[0], Tbracket) == 0) {
2619 if (strcmp(wp[--argc], "]") != 0) {
2620 bi_errorf("missing ]");
2621 return (T_ERR_EXIT);
2626 te.wp_end = wp + argc;
2629 * Attempt to conform to POSIX special cases. This is pretty
2630 * dumb code straight-forward from the 2008 spec, but unlike
2631 * the old pdksh code doesn't live from so many assumptions.
2632 * It does, though, inline some calls to '(*te.funcname)()'.
2643 if (ptest_isa(&te, TM_NOT)) {
2647 if ((op = ptest_isa(&te, TM_UNOP))) {
2649 rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
2651 if (te.flags & TEF_ERROR)
2652 return (T_ERR_EXIT);
2653 return ((invert & 1) ? rv : !rv);
2655 /* let the parser deal with anything else */
2660 /* use inside knowledge of ptest_getopnd inlined below */
2662 if ((op = ptest_isa(&te, TM_BINOP))) {
2663 /* test lhs op rhs */
2664 rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
2667 if (ptest_isa(&te, tm = TM_AND) || ptest_isa(&te, tm = TM_OR)) {
2669 argc = test_eval(&te, TO_STNZE, lhs, NULL, true);
2670 rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, true);
2677 /* back up to lhs */
2679 if (ptest_isa(&te, TM_NOT)) {
2683 if (ptest_isa(&te, TM_OPAREN)) {
2685 /* skip operand, without evaluation */
2687 /* check for closing parenthesis */
2688 op = ptest_isa(&te, TM_CPAREN);
2689 /* back up to operand */
2691 /* if there was a closing paren, handle it */
2694 /* backing up is done before calling the parser */
2696 /* let the parser deal with it */
2699 if (ptest_isa(&te, TM_NOT)) {
2703 if (ptest_isa(&te, TM_OPAREN)) {
2705 /* skip two operands, without evaluation */
2708 /* check for closing parenthesis */
2709 op = ptest_isa(&te, TM_CPAREN);
2710 /* back up to first operand */
2712 /* if there was a closing paren, handle it */
2715 /* backing up is done before calling the parser */
2717 /* defer this to the parser */
2721 /* "The results are unspecified." */
2723 return (test_parse(&te));
2727 * Generic test routines.
2731 test_isop(Test_meta meta, const char *s)
2734 const struct t_op *tbl;
2736 tbl = meta == TM_UNOP ? u_ops : b_ops;
2739 for (; tbl->op_text[0]; tbl++)
2740 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
2741 return (tbl->op_num);
2747 #define test_access(name, mode) access_ex(access, (name), (mode))
2748 #define test_stat(name, buffer) stat_ex((name), (buffer))
2750 #define test_access(name, mode) access((name), (mode))
2751 #define test_stat(name, buffer) stat((name), (buffer))
2755 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
2769 /* Binary operators */
2783 /* consistency check, but does not happen in practice */
2785 te->flags |= TEF_ERROR;
2790 /* for completeness of switch */
2803 return (*opnd1 != '\0');
2807 return (*opnd1 == '\0');
2811 return ((vp = isglobal(opnd1, false)) && (vp->flag & ISSET));
2815 if ((i = *opnd1) == '!' || i == '?')
2817 if ((k = option(opnd1)) == (size_t)-1)
2819 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
2823 /* LINTED use of access */
2824 return (test_access(opnd1, R_OK) == 0);
2828 /* LINTED use of access */
2829 return (test_access(opnd1, W_OK) == 0);
2833 return (ksh_access(opnd1, X_OK) == 0);
2839 return (test_stat(opnd1, &b1) == 0);
2843 return (test_stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
2847 return (stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
2851 return (stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
2855 return (stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
2859 return (stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
2863 #ifdef MKSH__NO_SYMLINK
2866 return (lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
2871 return (stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
2873 /* -H => HP context dependent files (directories) */
2880 * Append a + to filename and check to see if result is
2881 * a setuid directory. CDF stuff in general is hookey,
2882 * since it breaks for, e.g., the following sequence:
2883 * echo hi >foo+; mkdir foo; echo bye >foo/default;
2884 * chmod u+s foo (foo+ refers to the file with hi in it,
2885 * there is no way to get at the file with bye in it;
2886 * please correct me if I'm wrong about this).
2889 nv = shf_smprintf("%s+", opnd1);
2890 i = (stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
2900 return (stat(opnd1, &b1) == 0 &&
2901 (b1.st_mode & S_ISUID) == S_ISUID);
2905 return (stat(opnd1, &b1) == 0 &&
2906 (b1.st_mode & S_ISGID) == S_ISGID);
2911 return (stat(opnd1, &b1) == 0 &&
2912 (b1.st_mode & S_ISVTX) == S_ISVTX);
2919 return (stat(opnd1, &b1) == 0 && (off_t)b1.st_size > (off_t)0);
2923 if (opnd1 && !bi_getn(opnd1, &i)) {
2924 te->flags |= TEF_ERROR;
2927 i = isatty(opnd1 ? i : 0);
2932 return (stat(opnd1, &b1) == 0 && (uid_t)b1.st_uid == ksheuid);
2936 return (stat(opnd1, &b1) == 0 && (gid_t)b1.st_gid == getegid());
2944 if (te->flags & TEF_DBRACKET) {
2945 if ((i = gmatchx(opnd1, opnd2, false)))
2946 record_match(opnd1);
2949 return (strcmp(opnd1, opnd2) == 0);
2953 if (te->flags & TEF_DBRACKET) {
2954 if ((i = gmatchx(opnd1, opnd2, false)))
2955 record_match(opnd1);
2958 return (strcmp(opnd1, opnd2) != 0);
2962 return (strcmp(opnd1, opnd2) < 0);
2966 return (strcmp(opnd1, opnd2) > 0);
2980 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
2981 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
2982 /* error already printed.. */
2983 te->flags |= TEF_ERROR;
3008 * ksh88/ksh93 succeed if file2 can't be stated
3009 * (subtly different from 'does not exist').
3011 return (stat(opnd1, &b1) == 0 &&
3012 (((s = stat(opnd2, &b2)) == 0 &&
3013 b1.st_mtime > b2.st_mtime) || s < 0));
3018 * ksh88/ksh93 succeed if file1 can't be stated
3019 * (subtly different from 'does not exist').
3021 return (stat(opnd2, &b2) == 0 &&
3022 (((s = stat(opnd1, &b1)) == 0 &&
3023 b1.st_mtime < b2.st_mtime) || s < 0));
3027 return (stat (opnd1, &b1) == 0 && stat (opnd2, &b2) == 0 &&
3028 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
3030 /* all other cases */
3033 /* throw the error */
3036 (*te->error)(te, 0, "internal error: unknown op");
3041 test_parse(Test_env *te)
3045 rv = test_oexpr(te, 1);
3047 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3048 (*te->error)(te, 0, "unexpected operator/operand");
3050 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3054 test_oexpr(Test_env *te, bool do_eval)
3058 if ((rv = test_aexpr(te, do_eval)))
3060 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3061 return (test_oexpr(te, do_eval) || rv);
3066 test_aexpr(Test_env *te, bool do_eval)
3070 if (!(rv = test_nexpr(te, do_eval)))
3072 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3073 return (test_aexpr(te, do_eval) && rv);
3078 test_nexpr(Test_env *te, bool do_eval)
3080 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3081 return (!test_nexpr(te, do_eval));
3082 return (test_primary(te, do_eval));
3086 test_primary(Test_env *te, bool do_eval)
3088 const char *opnd1, *opnd2;
3092 if (te->flags & TEF_ERROR)
3094 if ((*te->isa)(te, TM_OPAREN)) {
3095 rv = test_oexpr(te, do_eval);
3096 if (te->flags & TEF_ERROR)
3098 if (!(*te->isa)(te, TM_CPAREN)) {
3099 (*te->error)(te, 0, "missing )");
3105 * Binary should have precedence over unary in this case
3106 * so that something like test \( -f = -f \) is accepted
3108 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3109 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3110 if ((op = (*te->isa)(te, TM_UNOP))) {
3111 /* unary expression */
3112 opnd1 = (*te->getopnd)(te, op, do_eval);
3114 (*te->error)(te, -1, Tno_args);
3118 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3121 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3123 (*te->error)(te, 0, "expression expected");
3126 if ((op = (*te->isa)(te, TM_BINOP))) {
3127 /* binary expression */
3128 opnd2 = (*te->getopnd)(te, op, do_eval);
3130 (*te->error)(te, -1, "missing second argument");
3134 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3136 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3140 * Plain test (test and [ .. ]) specific routines.
3144 * Test if the current token is a whatever. Accepts the current token if
3145 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3146 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3149 ptest_isa(Test_env *te, Test_meta meta)
3151 /* Order important - indexed by Test_meta values */
3152 static const char * const tokens[] = {
3153 "-o", "-a", "!", "(", ")"
3157 if (te->pos.wp >= te->wp_end)
3158 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3160 if (meta == TM_UNOP || meta == TM_BINOP)
3161 rv = test_isop(meta, *te->pos.wp);
3162 else if (meta == TM_END)
3165 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3166 TO_NONNULL : TO_NONOP;
3168 /* Accept the token? */
3176 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3178 if (te->pos.wp >= te->wp_end)
3179 return (op == TO_FILTT ? "1" : NULL);
3180 return (*te->pos.wp++);
3184 ptest_error(Test_env *te, int ofs, const char *msg)
3188 te->flags |= TEF_ERROR;
3189 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3190 bi_errorf(Tf_sD_s, op, msg);
3192 bi_errorf(Tf_s, msg);
3195 #ifndef MKSH_NO_LIMITS
3199 /* Magic to divine the 'm' and 'v' limits */
3202 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3203 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3204 #define ULIMIT_V_IS_AS
3205 #elif defined(RLIMIT_VMEM)
3206 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3207 #define ULIMIT_V_IS_AS
3209 #define ULIMIT_V_IS_VMEM
3215 #ifdef ULIMIT_V_IS_VMEM
3216 #define ULIMIT_M_IS_RSS
3217 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3218 #define ULIMIT_M_IS_VMEM
3220 #define ULIMIT_M_IS_RSS
3222 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3223 #undef ULIMIT_M_IS_RSS
3227 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3228 #define ULIMIT_V_IS_VMEM
3231 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3232 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3233 #define ULIMIT_M_IS_VMEM
3236 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3237 (RLIMIT_VMEM == RLIMIT_AS)
3238 #undef ULIMIT_M_IS_VMEM
3241 #if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
3242 # error nonsensical m ulimit
3245 #if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
3246 # error nonsensical v ulimit
3250 /* limit resource */
3252 /* multiply by to get rlim_{cur,max} values */
3253 unsigned int factor;
3260 #define RLIMITS_DEFNS
3261 #define FN(lname,lid,lfac,lopt) \
3262 static const struct { \
3264 unsigned int factor; \
3266 char name[sizeof(lname)]; \
3267 } rlimits_ ## lid = { \
3268 lid, lfac, lopt, lname \
3270 #include "rlimits.gen"
3272 static void print_ulimit(const struct limits *, int);
3273 static int set_ulimit(const struct limits *, const char *, int);
3275 static const struct limits * const rlimits[] = {
3276 #define RLIMITS_ITEMS
3277 #include "rlimits.gen"
3280 static const char rlimits_opts[] =
3281 #define RLIMITS_OPTCS
3282 #include "rlimits.gen"
3286 c_ulimit(const char **wp)
3289 int how = SOFT | HARD, optc, what = 'f';
3292 while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
3304 bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
3310 while (i < NELEM(rlimits)) {
3311 if (rlimits[i]->optchar == what)
3315 internal_warningf("ulimit: %c", what);
3318 if (wp[builtin_opt.optind]) {
3319 if (all || wp[builtin_opt.optind + 1]) {
3320 bi_errorf(Ttoo_many_args);
3323 return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
3326 print_ulimit(rlimits[i], how);
3327 else for (i = 0; i < NELEM(rlimits); ++i) {
3328 shprintf("-%c: %-20s ", rlimits[i]->optchar, rlimits[i]->name);
3329 print_ulimit(rlimits[i], how);
3335 set_ulimit(const struct limits *l, const char *v, int how)
3337 rlim_t val = (rlim_t)0;
3338 struct rlimit limit;
3340 if (strcmp(v, "unlimited") == 0)
3341 val = (rlim_t)RLIM_INFINITY;
3345 if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
3348 * Avoid problems caused by typos that evaluate misses due
3349 * to evaluating unset parameters to 0...
3350 * If this causes problems, will have to add parameter to
3351 * evaluate() to control if unset params are 0 or an error.
3353 if (!rval && !ksh_isdigit(v[0])) {
3354 bi_errorf("invalid %s limit: %s", l->name, v);
3357 val = (rlim_t)((rlim_t)rval * l->factor);
3360 if (getrlimit(l->resource, &limit) < 0) {
3362 bi_errorf("limit %s could not be read, contact the mksh developers: %s",
3363 l->name, cstrerror(errno));
3365 /* some can't be read */
3366 limit.rlim_cur = RLIM_INFINITY;
3367 limit.rlim_max = RLIM_INFINITY;
3370 limit.rlim_cur = val;
3372 limit.rlim_max = val;
3373 if (!setrlimit(l->resource, &limit))
3376 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3378 bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
3383 print_ulimit(const struct limits *l, int how)
3385 rlim_t val = (rlim_t)0;
3386 struct rlimit limit;
3388 if (getrlimit(l->resource, &limit)) {
3389 shf_puts("unknown\n", shl_stdout);
3393 val = limit.rlim_cur;
3394 else if (how & HARD)
3395 val = limit.rlim_max;
3396 if (val == (rlim_t)RLIM_INFINITY)
3397 shf_puts("unlimited\n", shl_stdout);
3399 shprintf("%lu\n", (unsigned long)(val / l->factor));
3404 c_rename(const char **wp)
3410 if (wp[0] && !strcmp(wp[0], "--"))
3411 /* skip "--" (options separator) */
3414 /* check for exactly two arguments */
3415 if (wp[0] == NULL /* first argument */ ||
3416 wp[1] == NULL /* second argument */ ||
3417 wp[2] != NULL /* no further args please */)
3419 else if ((rv = rename(wp[0], wp[1])) != 0) {
3421 bi_errorf(Tf_sD_s, "failed", cstrerror(rv));
3428 c_realpath(const char **wp)
3435 if (wp[0] && !strcmp(wp[0], "--"))
3436 /* skip "--" (options separator) */
3439 /* check for exactly one argument */
3440 if (wp[0] == NULL || wp[1] != NULL)
3442 else if ((buf = do_realpath(wp[0])) == NULL) {
3444 bi_errorf(Tf_sD_s, wp[0], cstrerror(rv));
3445 if ((unsigned int)rv > 255)
3448 shprintf(Tf_sN, buf);
3457 c_cat(const char **wp)
3459 int fd = STDIN_FILENO, rv;
3461 const char *fn = "<stdin>";
3464 #define MKSH_CAT_BUFSIZ 4096
3466 /* parse options: POSIX demands we support "-u" as no-op */
3467 while ((rv = ksh_getopt(wp, &builtin_opt, "u")) != -1) {
3470 /* we already operate unbuffered */
3477 wp += builtin_opt.optind;
3480 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3481 bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
3486 opipe = block_pipe();
3493 else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
3494 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3499 while (/* CONSTCOND */ 1) {
3500 if ((n = blocking_read(fd, (cp = buf),
3501 MKSH_CAT_BUFSIZ)) == -1) {
3502 if (errno == EINTR) {
3505 /* give the user a chance to ^C out */
3507 /* interrupted, try again */
3508 opipe = block_pipe();
3511 /* an error occured during reading */
3512 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3516 /* end of file reached */
3521 if ((w = write(STDOUT_FILENO, cp, n)) != -1) {
3526 if (errno == EINTR) {
3530 /* give the user a chance to ^C out */
3532 /* interrupted, try again */
3533 opipe = block_pipe();
3536 if (errno == EPIPE) {
3537 /* fake receiving signel */
3538 rv = ksh_sigmask(SIGPIPE);
3540 /* an error occured during writing */
3541 bi_errorf(Tf_sD_s, "<stdout>",
3545 if (fd != STDIN_FILENO)
3550 if (fd != STDIN_FILENO)
3563 c_sleep(const char **wp)
3570 if (wp[0] && !strcmp(wp[0], "--"))
3571 /* skip "--" (options separator) */
3574 if (!wp[0] || wp[1])
3576 else if (parse_usec(wp[0], &tv))
3577 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno), wp[0]);
3579 #ifndef MKSH_NOPROSPECTOFWORK
3580 sigset_t omask, bmask;
3582 /* block a number of signals from interrupting us, though */
3583 (void)sigemptyset(&bmask);
3584 (void)sigaddset(&bmask, SIGPIPE);
3585 (void)sigaddset(&bmask, SIGCHLD);
3587 (void)sigaddset(&bmask, SIGWINCH);
3590 (void)sigaddset(&bmask, SIGINFO);
3593 (void)sigaddset(&bmask, SIGUSR1);
3596 (void)sigaddset(&bmask, SIGUSR2);
3598 sigprocmask(SIG_BLOCK, &bmask, &omask);
3600 if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3602 * strictly speaking only for SIGALRM, but the
3603 * execution may be interrupted by other signals
3607 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
3608 #ifndef MKSH_NOPROSPECTOFWORK
3609 /* this will re-schedule signal delivery */
3610 sigprocmask(SIG_SETMASK, &omask, NULL);
3617 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
3619 c_suspend(const char **wp)
3621 if (wp[1] != NULL) {
3622 bi_errorf(Ttoo_many_args);
3626 /* Can't suspend an orphaned process group. */
3627 if (getpgid(kshppid) == getpgid(0) ||
3628 getsid(kshppid) != getsid(0)) {
3629 bi_errorf("can't suspend a login shell");