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 $ */
5
6 /*-
7 * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
8 * 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
9 * 2019, 2020
10 * mirabilos <m@mirbsd.org>
11 *
12 * Provided that these terms and disclaimer and all copyright notices
13 * are retained or reproduced in an accompanying document, permission
14 * is granted to deal in this work without restriction, including un-
15 * limited rights to use, publicly perform, distribute, sell, modify,
16 * merge, give away, or sublicence.
17 *
18 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
19 * the utmost extent permitted by applicable law, neither express nor
20 * implied; without malicious intent or gross negligence. In no event
21 * may a licensor, author or contributor be held liable for indirect,
22 * direct, other damage, loss, or other issues arising in any way out
23 * of dealing in the work, even if advised of the possibility of such
24 * damage or existence of a defect, except proven that it results out
25 * of said person's immediate fault when using the work as intended.
26 */
27
28 #include "sh.h"
29
30 #if HAVE_SELECT
31 #if HAVE_SYS_BSDTYPES_H
32 #include <sys/bsdtypes.h>
33 #endif
34 #if HAVE_SYS_SELECT_H
35 #include <sys/select.h>
36 #endif
37 #if HAVE_BSTRING_H
38 #include <bstring.h>
39 #endif
40 #endif
41
42 __RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.373 2020/05/16 22:38:21 tg Exp $");
43
44 #if HAVE_KILLPG
45 /*
46 * use killpg if < -1 since -1 does special things
47 * for some non-killpg-endowed kills
48 */
49 #define mksh_kill(p,s) ((p) < -1 ? killpg(-(p), (s)) : kill((p), (s)))
50 #else
51 /* cross fingers and hope kill is killpg-endowed */
52 #define mksh_kill kill
53 #endif
54
55 /* XXX conditions correct? */
56 #if !defined(RLIM_INFINITY) && !defined(MKSH_NO_LIMITS)
57 #define MKSH_NO_LIMITS 1
58 #endif
59
60 #ifdef MKSH_NO_LIMITS
61 #define c_ulimit c_true
62 #endif
63
64 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
65 static int c_suspend(const char **);
66 #endif
67
68 static int do_whence(const char **, int, bool, bool);
69
70 /* getn() that prints error */
71 static int
bi_getn(const char * as,int * ai)72 bi_getn(const char *as, int *ai)
73 {
74 int rv;
75
76 if (!(rv = getn(as, ai)))
77 bi_errorf(Tf_sD_s, Tbadnum, as);
78 return (rv);
79 }
80
81 static int
c_true(const char ** wp MKSH_A_UNUSED)82 c_true(const char **wp MKSH_A_UNUSED)
83 {
84 return (0);
85 }
86
87 static int
c_false(const char ** wp MKSH_A_UNUSED)88 c_false(const char **wp MKSH_A_UNUSED)
89 {
90 return (1);
91 }
92
93 /*
94 * A leading = means assignments before command are kept.
95 * A leading * means a POSIX special builtin.
96 * A leading ^ means declaration utility, - forwarder.
97 */
98 const struct builtin mkshbuiltins[] = {
99 {Tsgdot, c_dot},
100 {"*=:", c_true},
101 {Tbracket, c_test},
102 /* no =: AT&T manual wrong */
103 {Talias, c_alias},
104 {Tsgbreak, c_brkcont},
105 {T__builtin, c_builtin},
106 {Tbuiltin, c_builtin},
107 #if !defined(__ANDROID__)
108 {Tbcat, c_cat},
109 #endif
110 {Tcd, c_cd},
111 /* dash compatibility hack */
112 {"chdir", c_cd},
113 {T_command, c_command},
114 {Tsgcontinue, c_brkcont},
115 {"echo", c_print},
116 {"*=eval", c_eval},
117 {"*=exec", c_exec},
118 {"*=exit", c_exitreturn},
119 {Tdsgexport, c_typeset},
120 {Tfalse, c_false},
121 {"fc", c_fc},
122 {Tgetopts, c_getopts},
123 {Tjobs, c_jobs},
124 {"kill", c_kill},
125 {"let", c_let},
126 {"print", c_print},
127 {"pwd", c_pwd},
128 {Tread, c_read},
129 {Tdsgreadonly, c_typeset},
130 #if !defined(__ANDROID__)
131 {"!realpath", c_realpath},
132 #endif
133 {"~rename", c_rename},
134 {"*=return", c_exitreturn},
135 {Tsghset, c_set},
136 {"*=#shift", c_shift},
137 {Tgsource, c_dot},
138 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
139 {Tsuspend, c_suspend},
140 #endif
141 {"test", c_test},
142 {"*=times", c_times},
143 {"*=trap", c_trap},
144 {Ttrue, c_true},
145 {Tdgtypeset, c_typeset},
146 {"ulimit", c_ulimit},
147 {"umask", c_umask},
148 {Tunalias, c_unalias},
149 {"*=unset", c_unset},
150 {"wait", c_wait},
151 {"whence", c_whence},
152 #ifndef MKSH_UNEMPLOYED
153 {Tbg, c_fgbg},
154 {Tfg, c_fgbg},
155 #endif
156 #ifndef MKSH_NO_CMDLINE_EDITING
157 {"bind", c_bind},
158 #endif
159 #if HAVE_MKNOD
160 {"mknod", c_mknod},
161 #endif
162 #ifdef MKSH_PRINTF_BUILTIN
163 {"~printf", c_printf},
164 #endif
165 #if HAVE_SELECT
166 #if !defined(__ANDROID__)
167 {"sleep", c_sleep},
168 #endif
169 #endif
170 #ifdef __MirBSD__
171 /* alias to "true" for historical reasons */
172 {"domainname", c_true},
173 #endif
174 #ifdef __OS2__
175 {Textproc, c_true},
176 #endif
177 {NULL, (int (*)(const char **))NULL}
178 };
179
180 struct kill_info {
181 int num_width;
182 int name_width;
183 };
184
185 const struct t_op u_ops[] = {
186 /* 0*/ {"-a", TO_FILAXST },
187 {"-b", TO_FILBDEV },
188 {"-c", TO_FILCDEV },
189 {"-d", TO_FILID },
190 {"-e", TO_FILEXST },
191 {"-f", TO_FILREG },
192 {"-G", TO_FILGID },
193 {"-g", TO_FILSETG },
194 {"-H", TO_FILCDF },
195 {"-h", TO_FILSYM },
196 {"-k", TO_FILSTCK },
197 {"-L", TO_FILSYM },
198 /*12*/ {"-n", TO_STNZE },
199 {"-O", TO_FILUID },
200 /*14*/ {"-o", TO_OPTION },
201 {"-p", TO_FILFIFO },
202 /*16*/ {"-r", TO_FILRD },
203 {"-S", TO_FILSOCK },
204 {"-s", TO_FILGZ },
205 {"-t", TO_FILTT },
206 /*20*/ {"-u", TO_FILSETU },
207 {"-v", TO_ISSET },
208 {"-w", TO_FILWR },
209 /*23*/ {"-x", TO_FILEX },
210 {"-z", TO_STZER },
211 {"", TO_NONOP }
212 };
213 cta(u_ops_size, NELEM(u_ops) == 26);
214 const struct t_op b_ops[] = {
215 {"=", TO_STEQL },
216 {"==", TO_STEQL },
217 {"!=", TO_STNEQ },
218 {"<", TO_STLT },
219 {">", TO_STGT },
220 {"-eq", TO_INTEQ },
221 {"-ne", TO_INTNE },
222 {"-gt", TO_INTGT },
223 {"-ge", TO_INTGE },
224 {"-lt", TO_INTLT },
225 {"-le", TO_INTLE },
226 {"-ef", TO_FILEQ },
227 {"-nt", TO_FILNT },
228 {"-ot", TO_FILOT },
229 {"", TO_NONOP }
230 };
231
232 static int test_oexpr(Test_env *, bool);
233 static int test_aexpr(Test_env *, bool);
234 static int test_nexpr(Test_env *, bool);
235 static int test_primary(Test_env *, bool);
236 static Test_op ptest_isa(Test_env *, Test_meta);
237 static const char *ptest_getopnd(Test_env *, Test_op, bool);
238 static void ptest_error(Test_env *, int, const char *);
239 static void kill_fmt_entry(char *, size_t, unsigned int, const void *);
240 static void p_time(struct shf *, bool, long, int, int,
241 const char *, const char *);
242
243 int
c_pwd(const char ** wp)244 c_pwd(const char **wp)
245 {
246 int optc;
247 bool physical = tobool(Flag(FPHYSICAL));
248 char *p, *allocd = NULL;
249
250 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
251 switch (optc) {
252 case 'L':
253 physical = false;
254 break;
255 case 'P':
256 physical = true;
257 break;
258 case '?':
259 return (1);
260 }
261 wp += builtin_opt.optind;
262
263 if (wp[0]) {
264 bi_errorf(Ttoo_many_args);
265 return (1);
266 }
267 p = current_wd[0] ? (physical ? allocd = do_realpath(current_wd) :
268 current_wd) : NULL;
269 /* LINTED use of access */
270 if (p && access(p, R_OK) < 0)
271 p = NULL;
272 if (!p && !(p = allocd = ksh_get_wd())) {
273 bi_errorf(Tf_sD_s, "can't determine current directory",
274 cstrerror(errno));
275 return (1);
276 }
277 shprintf(Tf_sN, p);
278 afree(allocd, ATEMP);
279 return (0);
280 }
281
282 static const char *s_ptr;
283 static int s_get(void);
284 static void s_put(int);
285
286 int
c_print(const char ** wp)287 c_print(const char **wp)
288 {
289 int c;
290 const char *s;
291 char *xp;
292 XString xs;
293 struct {
294 /* storage for columnisation */
295 XPtrV words;
296 /* temporary storage for a wide character */
297 mksh_ari_t wc;
298 /* output file descriptor (if any) */
299 int fd;
300 /* temporary storage for a multibyte character */
301 char ts[4];
302 /* output word separator */
303 char ws;
304 /* output line separator */
305 char ls;
306 /* output a trailing line separator? */
307 bool nl;
308 /* expand backslash sequences? */
309 bool exp;
310 /* columnise output? */
311 bool col;
312 /* print to history instead of file descriptor / stdout? */
313 bool hist;
314 /* print words as wide characters? */
315 bool chars;
316 /* writing to a coprocess (SIGPIPE blocked)? */
317 bool coproc;
318 bool copipe;
319 } po;
320
321 memset(&po, 0, sizeof(po));
322 po.fd = 1;
323 po.ws = ' ';
324 po.ls = '\n';
325 po.nl = true;
326
327 if (wp[0][0] == 'e') {
328 /* "echo" builtin */
329 if (Flag(FPOSIX) ||
330 #ifndef MKSH_MIDNIGHTBSD01ASH_COMPAT
331 Flag(FSH) ||
332 #endif
333 as_builtin) {
334 /* BSD "echo" cmd, Debian Policy 10.4 compliant */
335 ++wp;
336 bsd_echo:
337 if (*wp && !strcmp(*wp, Tdn)) {
338 po.nl = false;
339 ++wp;
340 }
341 po.exp = false;
342 } else {
343 bool new_exp, new_nl = true;
344
345 /*-
346 * compromise between various historic echos: only
347 * recognise -Een if they appear in arguments with
348 * no illegal options; e.g. echo -nq outputs '-nq'
349 */
350 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
351 /* MidnightBSD /bin/sh needs -e supported but off */
352 if (Flag(FSH))
353 new_exp = false;
354 else
355 #endif
356 /* otherwise compromise on -e enabled by default */
357 new_exp = true;
358 goto print_tradparse_beg;
359
360 print_tradparse_arg:
361 if ((s = *wp) && *s++ == '-' && *s) {
362 print_tradparse_ch:
363 switch ((c = *s++)) {
364 case 'E':
365 new_exp = false;
366 goto print_tradparse_ch;
367 case 'e':
368 new_exp = true;
369 goto print_tradparse_ch;
370 case 'n':
371 new_nl = false;
372 goto print_tradparse_ch;
373 case '\0':
374 print_tradparse_beg:
375 po.exp = new_exp;
376 po.nl = new_nl;
377 ++wp;
378 goto print_tradparse_arg;
379 }
380 }
381 }
382 } else {
383 /* "print" builtin */
384 const char *opts = "AcelNnpRrsu,";
385 const char *emsg;
386
387 po.exp = true;
388
389 while ((c = ksh_getopt(wp, &builtin_opt, opts)) != -1)
390 switch (c) {
391 case 'A':
392 po.chars = true;
393 break;
394 case 'c':
395 po.col = true;
396 break;
397 case 'e':
398 po.exp = true;
399 break;
400 case 'l':
401 po.ws = '\n';
402 break;
403 case 'N':
404 po.ws = '\0';
405 po.ls = '\0';
406 break;
407 case 'n':
408 po.nl = false;
409 break;
410 case 'p':
411 if ((po.fd = coproc_getfd(W_OK, &emsg)) < 0) {
412 bi_errorf(Tf_coproc, emsg);
413 return (1);
414 }
415 break;
416 case 'R':
417 /* fake BSD echo but don't reset other flags */
418 wp += builtin_opt.optind;
419 goto bsd_echo;
420 case 'r':
421 po.exp = false;
422 break;
423 case 's':
424 po.hist = true;
425 break;
426 case 'u':
427 if (!*(s = builtin_opt.optarg))
428 po.fd = 0;
429 else if ((po.fd = check_fd(s, W_OK, &emsg)) < 0) {
430 bi_errorf("-u%s: %s", s, emsg);
431 return (1);
432 }
433 break;
434 case '?':
435 return (1);
436 }
437
438 if (!(builtin_opt.info & GI_MINUSMINUS)) {
439 /* treat a lone "-" like "--" */
440 if (wp[builtin_opt.optind] &&
441 ksh_isdash(wp[builtin_opt.optind]))
442 builtin_opt.optind++;
443 }
444 wp += builtin_opt.optind;
445 }
446
447 if (po.col) {
448 if (*wp == NULL)
449 return (0);
450
451 XPinit(po.words, 16);
452 }
453
454 Xinit(xs, xp, 128, ATEMP);
455
456 if (*wp == NULL)
457 goto print_no_arg;
458 print_read_arg:
459 if (po.chars) {
460 while (*wp != NULL) {
461 s = *wp++;
462 if (*s == '\0')
463 break;
464 if (!evaluate(s, &po.wc, KSH_RETURN_ERROR, true))
465 return (1);
466 Xcheck(xs, xp);
467 if (UTFMODE) {
468 po.ts[utf_wctomb(po.ts, po.wc)] = 0;
469 c = 0;
470 do {
471 Xput(xs, xp, po.ts[c]);
472 } while (po.ts[++c]);
473 } else
474 Xput(xs, xp, po.wc & 0xFF);
475 }
476 } else {
477 s = *wp++;
478 while ((c = *s++) != '\0') {
479 Xcheck(xs, xp);
480 if (po.exp && c == '\\') {
481 s_ptr = s;
482 c = unbksl(false, s_get, s_put);
483 s = s_ptr;
484 if (c == -1) {
485 /* rejected by generic function */
486 switch ((c = *s++)) {
487 case 'c':
488 po.nl = false;
489 /* AT&T brain damage */
490 continue;
491 case '\0':
492 --s;
493 c = '\\';
494 break;
495 default:
496 Xput(xs, xp, '\\');
497 }
498 } else if ((unsigned int)c > 0xFF) {
499 /* generic function returned UCS */
500 po.ts[utf_wctomb(po.ts, c - 0x100)] = 0;
501 c = 0;
502 do {
503 Xput(xs, xp, po.ts[c]);
504 } while (po.ts[++c]);
505 continue;
506 }
507 }
508 Xput(xs, xp, c);
509 }
510 }
511 if (po.col) {
512 Xput(xs, xp, '\0');
513 XPput(po.words, Xclose(xs, xp));
514 Xinit(xs, xp, 128, ATEMP);
515 }
516 if (*wp != NULL) {
517 if (!po.col)
518 Xput(xs, xp, po.ws);
519 goto print_read_arg;
520 }
521 if (po.col) {
522 size_t w = XPsize(po.words);
523 struct columnise_opts co;
524
525 XPput(po.words, NULL);
526 co.shf = shf_sopen(NULL, 128, SHF_WR | SHF_DYNAMIC, NULL);
527 co.linesep = po.ls;
528 co.prefcol = co.do_last = false;
529 pr_list(&co, (char **)XPptrv(po.words));
530 while (w--)
531 afree(XPptrv(po.words)[w], ATEMP);
532 XPfree(po.words);
533 w = co.shf->wp - co.shf->buf;
534 XcheckN(xs, xp, w);
535 memcpy(xp, co.shf->buf, w);
536 xp += w;
537 shf_sclose(co.shf);
538 }
539 print_no_arg:
540 if (po.nl)
541 Xput(xs, xp, po.ls);
542
543 c = 0;
544 if (po.hist) {
545 Xput(xs, xp, '\0');
546 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
547 } else {
548 size_t len = Xlength(xs, xp);
549
550 /*
551 * Ensure we aren't killed by a SIGPIPE while writing to
552 * a coprocess. AT&T ksh doesn't seem to do this (seems
553 * to just check that the co-process is alive which is
554 * not enough).
555 */
556 if (coproc.write >= 0 && coproc.write == po.fd) {
557 po.coproc = true;
558 po.copipe = block_pipe();
559 } else
560 po.coproc = po.copipe = false;
561
562 s = Xstring(xs, xp);
563 while (len > 0) {
564 ssize_t nwritten;
565
566 if ((nwritten = write(po.fd, s, len)) < 0) {
567 if (errno == EINTR) {
568 if (po.copipe)
569 restore_pipe();
570 /* give the user a chance to ^C out */
571 intrcheck();
572 /* interrupted, try again */
573 if (po.coproc)
574 po.copipe = block_pipe();
575 continue;
576 }
577 c = 1;
578 break;
579 }
580 s += nwritten;
581 len -= nwritten;
582 }
583 if (po.copipe)
584 restore_pipe();
585 }
586 Xfree(xs, xp);
587
588 return (c);
589 }
590
591 static int
s_get(void)592 s_get(void)
593 {
594 return (ord(*s_ptr++));
595 }
596
597 static void
s_put(int c MKSH_A_UNUSED)598 s_put(int c MKSH_A_UNUSED)
599 {
600 --s_ptr;
601 }
602
603 int
c_whence(const char ** wp)604 c_whence(const char **wp)
605 {
606 int optc;
607 bool pflag = false, vflag = false;
608
609 while ((optc = ksh_getopt(wp, &builtin_opt, Tpv)) != -1)
610 switch (optc) {
611 case 'p':
612 pflag = true;
613 break;
614 case 'v':
615 vflag = true;
616 break;
617 case '?':
618 return (1);
619 }
620 wp += builtin_opt.optind;
621
622 return (do_whence(wp, pflag ? FC_PATH :
623 FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, false));
624 }
625
626 /* note: command without -vV is dealt with in comexec() */
627 int
c_command(const char ** wp)628 c_command(const char **wp)
629 {
630 int optc, fcflags = FC_BI | FC_FUNC | FC_PATH | FC_WHENCE;
631 bool vflag = false;
632
633 while ((optc = ksh_getopt(wp, &builtin_opt, TpVv)) != -1)
634 switch (optc) {
635 case 'p':
636 fcflags |= FC_DEFPATH;
637 break;
638 case 'V':
639 vflag = true;
640 break;
641 case 'v':
642 vflag = false;
643 break;
644 case '?':
645 return (1);
646 }
647 wp += builtin_opt.optind;
648
649 return (do_whence(wp, fcflags, vflag, true));
650 }
651
652 static int
do_whence(const char ** wp,int fcflags,bool vflag,bool iscommand)653 do_whence(const char **wp, int fcflags, bool vflag, bool iscommand)
654 {
655 uint32_t h;
656 int rv = 0;
657 struct tbl *tp;
658 const char *id;
659
660 while ((vflag || rv == 0) && (id = *wp++) != NULL) {
661 h = hash(id);
662 tp = NULL;
663
664 if (fcflags & FC_WHENCE)
665 tp = ktsearch(&keywords, id, h);
666 if (!tp && (fcflags & FC_WHENCE)) {
667 tp = ktsearch(&aliases, id, h);
668 if (tp && !(tp->flag & ISSET))
669 tp = NULL;
670 }
671 if (!tp)
672 tp = findcom(id, fcflags);
673
674 switch (tp->type) {
675 case CSHELL:
676 case CFUNC:
677 case CKEYWD:
678 shf_puts(id, shl_stdout);
679 break;
680 }
681
682 switch (tp->type) {
683 case CSHELL:
684 if (vflag)
685 shprintf(" is a %sshell %s",
686 (tp->flag & SPEC_BI) ? "special " : "",
687 Tbuiltin);
688 break;
689 case CFUNC:
690 if (vflag) {
691 shf_puts(" is a", shl_stdout);
692 if (tp->flag & EXPORT)
693 shf_puts("n exported", shl_stdout);
694 if (tp->flag & TRACE)
695 shf_puts(" traced", shl_stdout);
696 if (!(tp->flag & ISSET)) {
697 shf_puts(" undefined", shl_stdout);
698 if (tp->u.fpath)
699 shprintf(" (autoload from %s)",
700 tp->u.fpath);
701 }
702 shf_puts(T_function, shl_stdout);
703 }
704 break;
705 case CEXEC:
706 case CTALIAS:
707 if (tp->flag & ISSET) {
708 if (vflag) {
709 shprintf("%s is ", id);
710 if (tp->type == CTALIAS)
711 shprintf("a tracked %s%s for ",
712 (tp->flag & EXPORT) ?
713 "exported " : "",
714 Talias);
715 }
716 shf_puts(tp->val.s, shl_stdout);
717 } else {
718 if (vflag)
719 shprintf(Tnot_found_s, id);
720 rv = 1;
721 }
722 break;
723 case CALIAS:
724 if (!vflag && iscommand)
725 shprintf(Tf_s_, Talias);
726 if (vflag || iscommand)
727 print_value_quoted(shl_stdout, id);
728 if (vflag)
729 shprintf(" is an %s%s for ",
730 (tp->flag & EXPORT) ? "exported " : "",
731 Talias);
732 else if (iscommand)
733 shf_putc('=', shl_stdout);
734 print_value_quoted(shl_stdout, tp->val.s);
735 break;
736 case CKEYWD:
737 if (vflag)
738 shf_puts(" is a reserved word", shl_stdout);
739 break;
740 #ifndef MKSH_SMALL
741 default:
742 bi_errorf(Tunexpected_type, id, Tcommand, tp->type);
743 return (1);
744 #endif
745 }
746 if (vflag || !rv)
747 shf_putc('\n', shl_stdout);
748 }
749 return (rv);
750 }
751
752 bool
valid_alias_name(const char * cp)753 valid_alias_name(const char *cp)
754 {
755 switch (ord(*cp)) {
756 case ORD('+'):
757 case ORD('-'):
758 return (false);
759 case ORD('['):
760 if (ord(cp[1]) == ORD('[') && !cp[2])
761 return (false);
762 break;
763 }
764 while (*cp)
765 if (ctype(*cp, C_ALIAS))
766 ++cp;
767 else
768 return (false);
769 return (true);
770 }
771
772 int
c_alias(const char ** wp)773 c_alias(const char **wp)
774 {
775 struct table *t = &aliases;
776 int rv = 0, prefix = 0;
777 bool rflag = false, tflag, Uflag = false, pflag = false, chkalias;
778 uint32_t xflag = 0;
779 int optc;
780
781 builtin_opt.flags |= GF_PLUSOPT;
782 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != -1) {
783 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
784 switch (optc) {
785 case 'd':
786 #ifdef MKSH_NOPWNAM
787 t = NULL; /* fix "alias -dt" */
788 #else
789 t = &homedirs;
790 #endif
791 break;
792 case 'p':
793 pflag = true;
794 break;
795 case 'r':
796 rflag = true;
797 break;
798 case 't':
799 t = &taliases;
800 break;
801 case 'U':
802 /*
803 * kludge for tracked alias initialization
804 * (don't do a path search, just make an entry)
805 */
806 Uflag = true;
807 break;
808 case 'x':
809 xflag = EXPORT;
810 break;
811 case '?':
812 return (1);
813 }
814 }
815 #ifdef MKSH_NOPWNAM
816 if (t == NULL)
817 return (0);
818 #endif
819 wp += builtin_opt.optind;
820
821 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp &&
822 ctype(wp[0][0], C_MINUS | C_PLUS) && wp[0][1] == '\0') {
823 prefix = wp[0][0];
824 wp++;
825 }
826
827 tflag = t == &taliases;
828 chkalias = t == &aliases;
829
830 /* "hash -r" means reset all the tracked aliases.. */
831 if (rflag) {
832 static const char *args[] = {
833 Tunalias, "-ta", NULL
834 };
835
836 if (!tflag || *wp) {
837 shprintf("%s: -r flag can only be used with -t"
838 " and without arguments\n", Talias);
839 return (1);
840 }
841 ksh_getopt_reset(&builtin_opt, GF_ERROR);
842 return (c_unalias(args));
843 }
844
845 if (*wp == NULL) {
846 struct tbl *ap, **p;
847
848 for (p = ktsort(t); (ap = *p++) != NULL; )
849 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
850 if (pflag)
851 shprintf(Tf_s_, Talias);
852 print_value_quoted(shl_stdout, ap->name);
853 if (prefix != '+') {
854 shf_putc('=', shl_stdout);
855 print_value_quoted(shl_stdout, ap->val.s);
856 }
857 shf_putc('\n', shl_stdout);
858 }
859 }
860
861 for (; *wp != NULL; wp++) {
862 const char *alias = *wp, *val, *newval;
863 char *xalias = NULL;
864 struct tbl *ap;
865 uint32_t h;
866
867 if ((val = cstrchr(alias, '='))) {
868 strndupx(xalias, alias, val++ - alias, ATEMP);
869 alias = xalias;
870 }
871 if (chkalias && !valid_alias_name(alias)) {
872 bi_errorf(Tinvname, alias, Talias);
873 afree(xalias, ATEMP);
874 return (1);
875 }
876 h = hash(alias);
877 if (val == NULL && !tflag && !xflag) {
878 ap = ktsearch(t, alias, h);
879 if (ap != NULL && (ap->flag&ISSET)) {
880 if (pflag)
881 shprintf(Tf_s_, Talias);
882 print_value_quoted(shl_stdout, ap->name);
883 if (prefix != '+') {
884 shf_putc('=', shl_stdout);
885 print_value_quoted(shl_stdout, ap->val.s);
886 }
887 shf_putc('\n', shl_stdout);
888 } else {
889 shprintf(Tf_s_s_sN, alias, Talias, Tnot_found);
890 rv = 1;
891 }
892 continue;
893 }
894 ap = ktenter(t, alias, h);
895 ap->type = tflag ? CTALIAS : CALIAS;
896 /* Are we setting the value or just some flags? */
897 if ((val && !tflag) || (!val && tflag && !Uflag)) {
898 if (ap->flag&ALLOC) {
899 ap->flag &= ~(ALLOC|ISSET);
900 afree(ap->val.s, APERM);
901 }
902 /* ignore values for -t (AT&T ksh does this) */
903 newval = tflag ?
904 search_path(alias, path, X_OK, NULL) :
905 val;
906 if (newval) {
907 strdupx(ap->val.s, newval, APERM);
908 ap->flag |= ALLOC|ISSET;
909 } else
910 ap->flag &= ~ISSET;
911 }
912 ap->flag |= DEFINED;
913 if (prefix == '+')
914 ap->flag &= ~xflag;
915 else
916 ap->flag |= xflag;
917 afree(xalias, ATEMP);
918 }
919
920 return (rv);
921 }
922
923 int
c_unalias(const char ** wp)924 c_unalias(const char **wp)
925 {
926 struct table *t = &aliases;
927 struct tbl *ap;
928 int optc, rv = 0;
929 bool all = false;
930
931 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
932 switch (optc) {
933 case 'a':
934 all = true;
935 break;
936 case 'd':
937 #ifdef MKSH_NOPWNAM
938 /* fix "unalias -dt" */
939 t = NULL;
940 #else
941 t = &homedirs;
942 #endif
943 break;
944 case 't':
945 t = &taliases;
946 break;
947 case '?':
948 return (1);
949 }
950 #ifdef MKSH_NOPWNAM
951 if (t == NULL)
952 return (0);
953 #endif
954 wp += builtin_opt.optind;
955
956 for (; *wp != NULL; wp++) {
957 ap = ktsearch(t, *wp, hash(*wp));
958 if (ap == NULL) {
959 /* POSIX */
960 rv = 1;
961 continue;
962 }
963 if (ap->flag&ALLOC) {
964 ap->flag &= ~(ALLOC|ISSET);
965 afree(ap->val.s, APERM);
966 }
967 ap->flag &= ~(DEFINED|ISSET|EXPORT);
968 }
969
970 if (all) {
971 struct tstate ts;
972
973 for (ktwalk(&ts, t); (ap = ktnext(&ts)); ) {
974 if (ap->flag&ALLOC) {
975 ap->flag &= ~(ALLOC|ISSET);
976 afree(ap->val.s, APERM);
977 }
978 ap->flag &= ~(DEFINED|ISSET|EXPORT);
979 }
980 }
981
982 return (rv);
983 }
984
985 int
c_let(const char ** wp)986 c_let(const char **wp)
987 {
988 int rv = 1;
989 mksh_ari_t val;
990
991 if (wp[1] == NULL)
992 /* AT&T ksh does this */
993 bi_errorf(Tno_args);
994 else
995 for (wp++; *wp; wp++)
996 if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
997 /* distinguish error from zero result */
998 rv = 2;
999 break;
1000 } else
1001 rv = val == 0;
1002 return (rv);
1003 }
1004
1005 int
c_jobs(const char ** wp)1006 c_jobs(const char **wp)
1007 {
1008 int optc, flag = 0, nflag = 0, rv = 0;
1009
1010 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != -1)
1011 switch (optc) {
1012 case 'l':
1013 flag = 1;
1014 break;
1015 case 'p':
1016 flag = 2;
1017 break;
1018 case 'n':
1019 nflag = 1;
1020 break;
1021 case 'z':
1022 /* debugging: print zombies */
1023 nflag = -1;
1024 break;
1025 case '?':
1026 return (1);
1027 }
1028 wp += builtin_opt.optind;
1029 if (!*wp) {
1030 if (j_jobs(NULL, flag, nflag))
1031 rv = 1;
1032 } else {
1033 for (; *wp; wp++)
1034 if (j_jobs(*wp, flag, nflag))
1035 rv = 1;
1036 }
1037 return (rv);
1038 }
1039
1040 #ifndef MKSH_UNEMPLOYED
1041 int
c_fgbg(const char ** wp)1042 c_fgbg(const char **wp)
1043 {
1044 bool bg = strcmp(*wp, Tbg) == 0;
1045 int rv = 0;
1046
1047 if (!Flag(FMONITOR)) {
1048 bi_errorf("job control not enabled");
1049 return (1);
1050 }
1051 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1052 return (1);
1053 wp += builtin_opt.optind;
1054 if (*wp)
1055 for (; *wp; wp++)
1056 rv = j_resume(*wp, bg);
1057 else
1058 rv = j_resume("%%", bg);
1059 /* fg returns $? of the job unless POSIX */
1060 return ((bg | Flag(FPOSIX)) ? 0 : rv);
1061 }
1062 #endif
1063
1064 /* format a single kill item */
1065 static void
kill_fmt_entry(char * buf,size_t buflen,unsigned int i,const void * arg)1066 kill_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
1067 {
1068 const struct kill_info *ki = (const struct kill_info *)arg;
1069
1070 i++;
1071 shf_snprintf(buf, buflen, "%*u %*s %s",
1072 ki->num_width, i,
1073 ki->name_width, sigtraps[i].name,
1074 sigtraps[i].mess);
1075 }
1076
1077 int
c_kill(const char ** wp)1078 c_kill(const char **wp)
1079 {
1080 Trap *t = NULL;
1081 const char *p;
1082 bool lflag = false;
1083 int i, n, rv, sig;
1084
1085 /* assume old style options if -digits or -UPPERCASE */
1086 if ((p = wp[1]) && *p == '-' && ctype(p[1], C_DIGIT | C_UPPER)) {
1087 if (!(t = gettrap(p + 1, false, false))) {
1088 bi_errorf(Tbad_sig_s, p + 1);
1089 return (1);
1090 }
1091 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1092 } else {
1093 int optc;
1094
1095 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
1096 switch (optc) {
1097 case 'l':
1098 lflag = true;
1099 break;
1100 case 's':
1101 if (!(t = gettrap(builtin_opt.optarg,
1102 true, false))) {
1103 bi_errorf(Tbad_sig_s,
1104 builtin_opt.optarg);
1105 return (1);
1106 }
1107 break;
1108 case '?':
1109 return (1);
1110 }
1111 i = builtin_opt.optind;
1112 }
1113 if ((lflag && t) || (!wp[i] && !lflag)) {
1114 #ifndef MKSH_SMALL
1115 shf_puts("usage:\tkill [-s signame | -signum | -signame]"
1116 " { job | pid | pgrp } ...\n"
1117 "\tkill -l [exit_status ...]\n", shl_out);
1118 #endif
1119 bi_errorfz();
1120 return (1);
1121 }
1122
1123 if (lflag) {
1124 if (wp[i]) {
1125 for (; wp[i]; i++) {
1126 if (!bi_getn(wp[i], &n))
1127 return (1);
1128 #if (ksh_NSIG <= 128)
1129 if (n > 128 && n < 128 + ksh_NSIG)
1130 n -= 128;
1131 #endif
1132 if (n > 0 && n < ksh_NSIG)
1133 shprintf(Tf_sN, sigtraps[n].name);
1134 else
1135 shprintf(Tf_dN, n);
1136 }
1137 } else if (Flag(FPOSIX)) {
1138 n = 1;
1139 while (n < ksh_NSIG) {
1140 shf_puts(sigtraps[n].name, shl_stdout);
1141 shf_putc(++n == ksh_NSIG ? '\n' : ' ',
1142 shl_stdout);
1143 }
1144 } else {
1145 ssize_t w, mess_cols = 0, mess_octs = 0;
1146 int j = ksh_NSIG - 1;
1147 struct kill_info ki = { 0, 0 };
1148 struct columnise_opts co;
1149
1150 do {
1151 ki.num_width++;
1152 } while ((j /= 10));
1153
1154 for (j = 1; j < ksh_NSIG; j++) {
1155 w = strlen(sigtraps[j].name);
1156 if (w > ki.name_width)
1157 ki.name_width = w;
1158 w = strlen(sigtraps[j].mess);
1159 if (w > mess_octs)
1160 mess_octs = w;
1161 w = utf_mbswidth(sigtraps[j].mess);
1162 if (w > mess_cols)
1163 mess_cols = w;
1164 }
1165
1166 co.shf = shl_stdout;
1167 co.linesep = '\n';
1168 co.prefcol = co.do_last = true;
1169
1170 print_columns(&co, (unsigned int)(ksh_NSIG - 1),
1171 kill_fmt_entry, (void *)&ki,
1172 ki.num_width + 1 + ki.name_width + 1 + mess_octs,
1173 ki.num_width + 1 + ki.name_width + 1 + mess_cols);
1174 }
1175 return (0);
1176 }
1177 rv = 0;
1178 sig = t ? t->signal : SIGTERM;
1179 for (; (p = wp[i]); i++) {
1180 if (*p == '%') {
1181 if (j_kill(p, sig))
1182 rv = 1;
1183 } else if (!getn(p, &n)) {
1184 bi_errorf(Tf_sD_s, p,
1185 "arguments must be jobs or process IDs");
1186 rv = 1;
1187 } else {
1188 if (mksh_kill(n, sig) < 0) {
1189 bi_errorf(Tf_sD_s, p, cstrerror(errno));
1190 rv = 1;
1191 }
1192 }
1193 }
1194 return (rv);
1195 }
1196
1197 void
getopts_reset(int val)1198 getopts_reset(int val)
1199 {
1200 if (val >= 1) {
1201 ksh_getopt_reset(&user_opt, GF_NONAME |
1202 (Flag(FPOSIX) ? 0 : GF_PLUSOPT));
1203 user_opt.optind = user_opt.uoptind = val;
1204 }
1205 }
1206
1207 int
c_getopts(const char ** wp)1208 c_getopts(const char **wp)
1209 {
1210 int argc, optc, rv;
1211 const char *opts, *var;
1212 char buf[3];
1213 struct tbl *vq, *voptarg;
1214
1215 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1216 return (1);
1217 wp += builtin_opt.optind;
1218
1219 opts = *wp++;
1220 if (!opts) {
1221 bi_errorf(Tf_sD_s, "options", Tno_args);
1222 return (1);
1223 }
1224
1225 var = *wp++;
1226 if (!var) {
1227 bi_errorf(Tf_sD_s, Tname, Tno_args);
1228 return (1);
1229 }
1230 if (!*var || *skip_varname(var, true)) {
1231 bi_errorf(Tf_sD_s, var, Tnot_ident);
1232 return (1);
1233 }
1234
1235 if (e->loc->next == NULL) {
1236 internal_warningf(Tf_sD_s, Tgetopts, Tno_args);
1237 return (1);
1238 }
1239 /* Which arguments are we parsing... */
1240 if (*wp == NULL)
1241 wp = e->loc->next->argv;
1242 else
1243 *--wp = e->loc->next->argv[0];
1244
1245 /* Check that our saved state won't cause a core dump... */
1246 for (argc = 0; wp[argc]; argc++)
1247 ;
1248 if (user_opt.optind > argc ||
1249 (user_opt.p != 0 &&
1250 user_opt.p > strlen(wp[user_opt.optind - 1]))) {
1251 bi_errorf("arguments changed since last call");
1252 return (1);
1253 }
1254
1255 user_opt.optarg = NULL;
1256 optc = ksh_getopt(wp, &user_opt, opts);
1257
1258 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1259 buf[0] = '+';
1260 buf[1] = optc;
1261 buf[2] = '\0';
1262 } else {
1263 /*
1264 * POSIX says var is set to ? at end-of-options, AT&T ksh
1265 * sets it to null - we go with POSIX...
1266 */
1267 buf[0] = optc < 0 ? '?' : optc;
1268 buf[1] = '\0';
1269 }
1270
1271 /* AT&T ksh93 in fact does change OPTIND for unknown options too */
1272 user_opt.uoptind = user_opt.optind;
1273
1274 voptarg = global("OPTARG");
1275 /* AT&T ksh clears ro and int */
1276 voptarg->flag &= ~RDONLY;
1277 /* Paranoia: ensure no bizarre results. */
1278 if (voptarg->flag & INTEGER)
1279 typeset("OPTARG", 0, INTEGER, 0, 0);
1280 if (user_opt.optarg == NULL)
1281 unset(voptarg, 1);
1282 else
1283 /* this can't fail (haing cleared readonly/integer) */
1284 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1285
1286 rv = 0;
1287
1288 vq = global(var);
1289 /* Error message already printed (integer, readonly) */
1290 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1291 rv = 2;
1292 if (Flag(FEXPORT))
1293 typeset(var, EXPORT, 0, 0, 0);
1294
1295 return (optc < 0 ? 1 : rv);
1296 }
1297
1298 #ifndef MKSH_NO_CMDLINE_EDITING
1299 int
c_bind(const char ** wp)1300 c_bind(const char **wp)
1301 {
1302 int optc, rv = 0;
1303 #ifndef MKSH_SMALL
1304 bool macro = false;
1305 #endif
1306
1307 if (x_bind_check()) {
1308 bi_errorf("can't bind, not a tty");
1309 return (1);
1310 }
1311
1312 while ((optc = ksh_getopt(wp, &builtin_opt, "lm")) != -1)
1313 switch (optc) {
1314 case 'l':
1315 return (x_bind_list());
1316 #ifndef MKSH_SMALL
1317 case 'm':
1318 macro = true;
1319 break;
1320 #endif
1321 default:
1322 return (1);
1323 }
1324 wp += builtin_opt.optind;
1325
1326 if (*wp == NULL)
1327 return (x_bind_showall());
1328
1329 do {
1330 rv |= x_bind(*wp SMALLP(macro));
1331 } while (*++wp);
1332
1333 return (rv);
1334 }
1335 #endif
1336
1337 int
c_shift(const char ** wp)1338 c_shift(const char **wp)
1339 {
1340 int n;
1341 mksh_ari_t val;
1342 const char *arg;
1343 struct block *l = e->loc;
1344
1345 if ((l->flags & BF_RESETSPEC)) {
1346 /* prevent pollution */
1347 l->flags &= ~BF_RESETSPEC;
1348 /* operate on parent environment */
1349 l = l->next;
1350 }
1351
1352 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1353 return (1);
1354 arg = wp[builtin_opt.optind];
1355
1356 if (!arg)
1357 n = 1;
1358 else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
1359 /* error already printed */
1360 bi_errorfz();
1361 return (1);
1362 } else if (!(n = val)) {
1363 /* nothing to do */
1364 return (0);
1365 } else if (n < 0) {
1366 bi_errorf(Tf_sD_s, Tbadnum, arg);
1367 return (1);
1368 }
1369
1370 if (l->argc < n) {
1371 bi_errorf("nothing to shift");
1372 return (1);
1373 }
1374 l->argv[n] = l->argv[0];
1375 l->argv += n;
1376 l->argc -= n;
1377 return (0);
1378 }
1379
1380 int
c_umask(const char ** wp)1381 c_umask(const char **wp)
1382 {
1383 int i, optc;
1384 const char *cp;
1385 bool symbolic = false;
1386 mode_t old_umask;
1387
1388 while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
1389 switch (optc) {
1390 case 'S':
1391 symbolic = true;
1392 break;
1393 case '?':
1394 return (1);
1395 }
1396 cp = wp[builtin_opt.optind];
1397 if (cp == NULL) {
1398 old_umask = umask((mode_t)0);
1399 umask(old_umask);
1400 if (symbolic) {
1401 char buf[18], *p;
1402 int j;
1403
1404 old_umask = ~old_umask;
1405 p = buf;
1406 for (i = 0; i < 3; i++) {
1407 *p++ = Tugo[i];
1408 *p++ = '=';
1409 for (j = 0; j < 3; j++)
1410 if (old_umask & (1 << (8 - (3*i + j))))
1411 *p++ = "rwx"[j];
1412 *p++ = ',';
1413 }
1414 p[-1] = '\0';
1415 shprintf(Tf_sN, buf);
1416 } else
1417 shprintf("%#3.3o\n", (unsigned int)old_umask);
1418 } else {
1419 mode_t new_umask;
1420
1421 if (ctype(*cp, C_DIGIT)) {
1422 new_umask = 0;
1423 while (ctype(*cp, C_OCTAL)) {
1424 new_umask = new_umask * 8 + ksh_numdig(*cp);
1425 ++cp;
1426 }
1427 if (*cp) {
1428 bi_errorf(Tbadnum);
1429 return (1);
1430 }
1431 } else {
1432 /* symbolic format */
1433 int positions, new_val;
1434 char op;
1435
1436 old_umask = umask((mode_t)0);
1437 /* in case of error */
1438 umask(old_umask);
1439 old_umask = ~old_umask;
1440 new_umask = old_umask;
1441 positions = 0;
1442 while (*cp) {
1443 while (*cp && vstrchr(Taugo, *cp))
1444 switch (*cp++) {
1445 case 'a':
1446 positions |= 0111;
1447 break;
1448 case 'u':
1449 positions |= 0100;
1450 break;
1451 case 'g':
1452 positions |= 0010;
1453 break;
1454 case 'o':
1455 positions |= 0001;
1456 break;
1457 }
1458 if (!positions)
1459 /* default is a */
1460 positions = 0111;
1461 if (!ctype((op = *cp), C_EQUAL | C_MINUS | C_PLUS))
1462 break;
1463 cp++;
1464 new_val = 0;
1465 while (*cp && vstrchr("rwxugoXs", *cp))
1466 switch (*cp++) {
1467 case 'r': new_val |= 04; break;
1468 case 'w': new_val |= 02; break;
1469 case 'x': new_val |= 01; break;
1470 case 'u':
1471 new_val |= old_umask >> 6;
1472 break;
1473 case 'g':
1474 new_val |= old_umask >> 3;
1475 break;
1476 case 'o':
1477 new_val |= old_umask >> 0;
1478 break;
1479 case 'X':
1480 if (old_umask & 0111)
1481 new_val |= 01;
1482 break;
1483 case 's':
1484 /* ignored */
1485 break;
1486 }
1487 new_val = (new_val & 07) * positions;
1488 switch (op) {
1489 case '-':
1490 new_umask &= ~new_val;
1491 break;
1492 case '=':
1493 new_umask = new_val |
1494 (new_umask & ~(positions * 07));
1495 break;
1496 case '+':
1497 new_umask |= new_val;
1498 }
1499 if (*cp == ',') {
1500 positions = 0;
1501 cp++;
1502 } else if (!ctype(*cp, C_EQUAL | C_MINUS | C_PLUS))
1503 break;
1504 }
1505 if (*cp) {
1506 bi_errorf("bad mask");
1507 return (1);
1508 }
1509 new_umask = ~new_umask;
1510 }
1511 umask(new_umask);
1512 }
1513 return (0);
1514 }
1515
1516 int
c_dot(const char ** wp)1517 c_dot(const char **wp)
1518 {
1519 const char *file, *cp, **argv;
1520 int argc, rv, errcode;
1521
1522 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1523 return (1);
1524
1525 if ((cp = wp[builtin_opt.optind]) == NULL) {
1526 bi_errorf(Tno_args);
1527 return (1);
1528 }
1529 file = search_path(cp, path, R_OK, &errcode);
1530 if (!file && errcode == ENOENT && wp[0][0] == 's' &&
1531 search_access(cp, R_OK) == 0)
1532 file = cp;
1533 if (!file) {
1534 bi_errorf(Tf_sD_s, cp, cstrerror(errcode));
1535 return (1);
1536 }
1537
1538 /* Set positional parameters? */
1539 if (wp[builtin_opt.optind + 1]) {
1540 argv = wp + builtin_opt.optind;
1541 /* preserve $0 */
1542 argv[0] = e->loc->argv[0];
1543 for (argc = 0; argv[argc + 1]; argc++)
1544 ;
1545 } else {
1546 argc = 0;
1547 argv = NULL;
1548 }
1549 /* SUSv4: OR with a high value never written otherwise */
1550 exstat |= 0x4000;
1551 if ((rv = include(file, argc, argv, false)) < 0) {
1552 /* should not happen */
1553 bi_errorf(Tf_sD_s, cp, cstrerror(errno));
1554 return (1);
1555 }
1556 if (exstat & 0x4000)
1557 /* detect old exstat, use 0 in that case */
1558 rv = 0;
1559 return (rv);
1560 }
1561
1562 int
c_wait(const char ** wp)1563 c_wait(const char **wp)
1564 {
1565 int rv = 0, sig;
1566
1567 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1568 return (1);
1569 wp += builtin_opt.optind;
1570 if (*wp == NULL) {
1571 while (waitfor(NULL, &sig) >= 0)
1572 ;
1573 rv = sig;
1574 } else {
1575 for (; *wp; wp++)
1576 rv = waitfor(*wp, &sig);
1577 if (rv < 0)
1578 /* magic exit code: bad job-id */
1579 rv = sig ? sig : 127;
1580 }
1581 return (rv);
1582 }
1583
1584 int
c_read(const char ** wp)1585 c_read(const char **wp)
1586 {
1587 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
1588 int c, fd = 0, rv = 0;
1589 bool savehist = false, intoarray = false, aschars = false;
1590 bool rawmode = false, expanding = false;
1591 bool lastparmmode = false, lastparmused = false;
1592 enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
1593 char delim = '\n';
1594 size_t bytesleft = 128, bytesread;
1595 struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
1596 char *cp, *allocd = NULL, *xp;
1597 const char *ccp;
1598 XString xs;
1599 size_t xsave = 0;
1600 mksh_ttyst tios;
1601 bool restore_tios = false;
1602 /* to catch read -aN2 foo[i] */
1603 bool subarray = false;
1604 #if HAVE_SELECT
1605 bool hastimeout = false;
1606 struct timeval tv, tvlim;
1607 #define c_read_opts "Aad:N:n:prst:u,"
1608 #else
1609 #define c_read_opts "Aad:N:n:prsu,"
1610 #endif
1611 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1612 int saved_mode;
1613 int saved_errno;
1614 #endif
1615
1616 while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
1617 switch (c) {
1618 case 'a':
1619 aschars = true;
1620 /* FALLTHROUGH */
1621 case 'A':
1622 intoarray = true;
1623 break;
1624 case 'd':
1625 delim = builtin_opt.optarg[0];
1626 break;
1627 case 'N':
1628 case 'n':
1629 readmode = c == 'N' ? BYTES : UPTO;
1630 if (!bi_getn(builtin_opt.optarg, &c))
1631 return (2);
1632 if (c == -1) {
1633 readmode = readmode == BYTES ? READALL : UPTO;
1634 bytesleft = 1024;
1635 } else
1636 bytesleft = (unsigned int)c;
1637 break;
1638 case 'p':
1639 if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
1640 bi_errorf(Tf_coproc, ccp);
1641 return (2);
1642 }
1643 break;
1644 case 'r':
1645 rawmode = true;
1646 break;
1647 case 's':
1648 savehist = true;
1649 break;
1650 #if HAVE_SELECT
1651 case 't':
1652 if (parse_usec(builtin_opt.optarg, &tv)) {
1653 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno),
1654 builtin_opt.optarg);
1655 return (2);
1656 }
1657 hastimeout = true;
1658 break;
1659 #endif
1660 case 'u':
1661 if (!builtin_opt.optarg[0])
1662 fd = 0;
1663 else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
1664 bi_errorf(Tf_sD_sD_s, Tdu, builtin_opt.optarg, ccp);
1665 return (2);
1666 }
1667 break;
1668 case '?':
1669 return (2);
1670 }
1671 wp += builtin_opt.optind;
1672 if (*wp == NULL)
1673 *--wp = TREPLY;
1674
1675 if (intoarray && wp[1] != NULL) {
1676 bi_errorf(Ttoo_many_args);
1677 return (2);
1678 }
1679
1680 if ((ccp = cstrchr(*wp, '?')) != NULL) {
1681 strdupx(allocd, *wp, ATEMP);
1682 allocd[ccp - *wp] = '\0';
1683 *wp = allocd;
1684 if (isatty(fd)) {
1685 /*
1686 * AT&T ksh says it prints prompt on fd if it's open
1687 * for writing and is a tty, but it doesn't do it
1688 * (it also doesn't check the interactive flag,
1689 * as is indicated in the Korn Shell book).
1690 */
1691 shf_puts(ccp + 1, shl_out);
1692 shf_flush(shl_out);
1693 }
1694 }
1695
1696 Xinit(xs, xp, bytesleft, ATEMP);
1697
1698 if (readmode == LINES)
1699 bytesleft = 1;
1700 else if (isatty(fd)) {
1701 x_mkraw(fd, &tios, true);
1702 restore_tios = true;
1703 }
1704
1705 #if HAVE_SELECT
1706 if (hastimeout) {
1707 mksh_TIME(tvlim);
1708 timeradd(&tvlim, &tv, &tvlim);
1709 }
1710 #endif
1711
1712 c_read_readloop:
1713 #if HAVE_SELECT
1714 if (hastimeout) {
1715 fd_set fdset;
1716
1717 FD_ZERO(&fdset);
1718 FD_SET((unsigned int)fd, &fdset);
1719 mksh_TIME(tv);
1720 timersub(&tvlim, &tv, &tv);
1721 if (tv.tv_sec < 0) {
1722 /* timeout expired globally */
1723 rv = 3;
1724 goto c_read_out;
1725 }
1726
1727 switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
1728 case 1:
1729 break;
1730 case 0:
1731 /* timeout expired for this call */
1732 bytesread = 0;
1733 rv = 3;
1734 goto c_read_readdone;
1735 default:
1736 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
1737 rv = 2;
1738 goto c_read_out;
1739 }
1740 }
1741 #endif
1742
1743 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1744 saved_mode = setmode(fd, O_TEXT);
1745 #endif
1746 if ((bytesread = blocking_read(fd, xp, bytesleft)) == (size_t)-1) {
1747 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1748 saved_errno = errno;
1749 setmode(fd, saved_mode);
1750 errno = saved_errno;
1751 #endif
1752 if (errno == EINTR) {
1753 /* check whether the signal would normally kill */
1754 if (!fatal_trap_check()) {
1755 /* no, just ignore the signal */
1756 goto c_read_readloop;
1757 }
1758 /* pretend the read was killed */
1759 } else {
1760 /* unexpected error */
1761 bi_errorf(Tf_s, cstrerror(errno));
1762 }
1763 rv = 2;
1764 goto c_read_out;
1765 }
1766 #if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
1767 setmode(fd, saved_mode);
1768 #endif
1769
1770 switch (readmode) {
1771 case READALL:
1772 if (bytesread == 0) {
1773 /* end of file reached */
1774 rv = 1;
1775 goto c_read_readdone;
1776 }
1777 xp += bytesread;
1778 XcheckN(xs, xp, bytesleft);
1779 break;
1780
1781 case UPTO:
1782 if (bytesread == 0)
1783 /* end of file reached */
1784 rv = 1;
1785 xp += bytesread;
1786 goto c_read_readdone;
1787
1788 case BYTES:
1789 if (bytesread == 0) {
1790 /* end of file reached */
1791 rv = 1;
1792 /* may be partial read: $? = 1, but content */
1793 goto c_read_readdone;
1794 }
1795 xp += bytesread;
1796 if ((bytesleft -= bytesread) == 0)
1797 goto c_read_readdone;
1798 break;
1799 case LINES:
1800 if (bytesread == 0) {
1801 /* end of file reached */
1802 rv = 1;
1803 goto c_read_readdone;
1804 }
1805 if ((c = *xp) == '\0' && !aschars && delim != '\0') {
1806 /* skip any read NULs unless delimiter */
1807 break;
1808 }
1809 if (expanding) {
1810 expanding = false;
1811 if (c == delim) {
1812 if (Flag(FTALKING_I) && isatty(fd)) {
1813 /*
1814 * set prompt in case this is
1815 * called from .profile or $ENV
1816 */
1817 set_prompt(PS2, NULL);
1818 pprompt(prompt, 0);
1819 }
1820 /* drop the backslash */
1821 --xp;
1822 /* and the delimiter */
1823 break;
1824 }
1825 } else if (c == delim) {
1826 goto c_read_readdone;
1827 } else if (!rawmode && c == '\\') {
1828 expanding = true;
1829 }
1830 Xcheck(xs, xp);
1831 ++xp;
1832 break;
1833 }
1834 goto c_read_readloop;
1835
1836 c_read_readdone:
1837 bytesread = Xlength(xs, xp);
1838 Xput(xs, xp, '\0');
1839
1840 /*-
1841 * state: we finished reading the input and NUL terminated it
1842 * Xstring(xs, xp) -> xp-1 = input string without trailing delim
1843 * rv = 3 if timeout, 1 if EOF, 0 otherwise (errors handled already)
1844 */
1845
1846 if (rv) {
1847 /* clean up coprocess if needed, on EOF/error/timeout */
1848 coproc_read_close(fd);
1849 if (readmode == READALL && (rv == 1 || (rv == 3 && bytesread)))
1850 /* EOF is no error here */
1851 rv = 0;
1852 }
1853
1854 if (savehist)
1855 histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
1856
1857 ccp = cp = Xclose(xs, xp);
1858 expanding = false;
1859 XinitN(xs, 128, ATEMP);
1860 if (intoarray) {
1861 vp = global(*wp);
1862 subarray = last_lookup_was_array;
1863 if (vp->flag & RDONLY) {
1864 c_read_splitro:
1865 bi_errorf(Tf_ro, *wp);
1866 c_read_spliterr:
1867 rv = 2;
1868 afree(cp, ATEMP);
1869 goto c_read_out;
1870 }
1871 /* counter for array index */
1872 c = subarray ? arrayindex(vp) : 0;
1873 /* exporting an array is currently pointless */
1874 unset(vp, subarray ? 0 : 1);
1875 }
1876 if (!aschars) {
1877 /* skip initial IFS whitespace */
1878 while (bytesread && is_ifsws(*ccp)) {
1879 ++ccp;
1880 --bytesread;
1881 }
1882 /* trim trailing IFS whitespace */
1883 while (bytesread && is_ifsws(ccp[bytesread - 1])) {
1884 --bytesread;
1885 }
1886 }
1887 c_read_splitloop:
1888 xp = Xstring(xs, xp);
1889 /* generate next word */
1890 if (!bytesread) {
1891 /* no more input */
1892 if (intoarray)
1893 goto c_read_splitdone;
1894 /* zero out next parameters */
1895 goto c_read_gotword;
1896 }
1897 if (aschars) {
1898 Xput(xs, xp, '1');
1899 Xput(xs, xp, '#');
1900 bytesleft = utf_ptradj(ccp);
1901 while (bytesleft && bytesread) {
1902 *xp++ = *ccp++;
1903 --bytesleft;
1904 --bytesread;
1905 }
1906 if (xp[-1] == '\0') {
1907 xp[-1] = '0';
1908 xp[-3] = '2';
1909 }
1910 goto c_read_gotword;
1911 }
1912
1913 if (!intoarray && wp[1] == NULL)
1914 lastparmmode = true;
1915
1916 c_read_splitlast:
1917 /* copy until IFS character */
1918 while (bytesread) {
1919 char ch;
1920
1921 ch = *ccp;
1922 if (expanding) {
1923 expanding = false;
1924 goto c_read_splitcopy;
1925 } else if (ctype(ch, C_IFS)) {
1926 break;
1927 } else if (!rawmode && ch == '\\') {
1928 expanding = true;
1929 } else {
1930 c_read_splitcopy:
1931 Xcheck(xs, xp);
1932 Xput(xs, xp, ch);
1933 }
1934 ++ccp;
1935 --bytesread;
1936 }
1937 xsave = Xsavepos(xs, xp);
1938 /* copy word delimiter: IFSWS+IFS,IFSWS */
1939 expanding = false;
1940 while (bytesread) {
1941 char ch;
1942
1943 ch = *ccp;
1944 if (!ctype(ch, C_IFS))
1945 break;
1946 if (lastparmmode && !expanding && !rawmode && ch == '\\') {
1947 expanding = true;
1948 } else {
1949 Xcheck(xs, xp);
1950 Xput(xs, xp, ch);
1951 }
1952 ++ccp;
1953 --bytesread;
1954 if (expanding)
1955 continue;
1956 if (!ctype(ch, C_IFSWS))
1957 break;
1958 }
1959 while (bytesread && is_ifsws(*ccp)) {
1960 Xcheck(xs, xp);
1961 Xput(xs, xp, *ccp);
1962 ++ccp;
1963 --bytesread;
1964 }
1965 /* if no more parameters, rinse and repeat */
1966 if (lastparmmode && bytesread) {
1967 lastparmused = true;
1968 goto c_read_splitlast;
1969 }
1970 /* get rid of the delimiter unless we pack the rest */
1971 if (!lastparmused)
1972 xp = Xrestpos(xs, xp, xsave);
1973 c_read_gotword:
1974 Xput(xs, xp, '\0');
1975 if (intoarray) {
1976 if (subarray) {
1977 /* array element passed, accept first read */
1978 if (vq) {
1979 bi_errorf("nested arrays not yet supported");
1980 goto c_read_spliterr;
1981 }
1982 vq = vp;
1983 if (c)
1984 /* [0] doesn't */
1985 vq->flag |= AINDEX;
1986 } else
1987 vq = arraysearch(vp, c++);
1988 } else {
1989 vq = global(*wp);
1990 /* must be checked before exporting */
1991 if (vq->flag & RDONLY)
1992 goto c_read_splitro;
1993 if (Flag(FEXPORT))
1994 typeset(*wp, EXPORT, 0, 0, 0);
1995 }
1996 if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
1997 goto c_read_spliterr;
1998 if (aschars) {
1999 setint_v(vq, vq, false);
2000 /* protect from UTFMODE changes */
2001 vq->type = 0;
2002 }
2003 if (intoarray || *++wp != NULL)
2004 goto c_read_splitloop;
2005
2006 c_read_splitdone:
2007 /* free up */
2008 afree(cp, ATEMP);
2009
2010 c_read_out:
2011 afree(allocd, ATEMP);
2012 Xfree(xs, xp);
2013 if (restore_tios)
2014 mksh_tcset(fd, &tios);
2015 return (rv == 3 ? ksh_sigmask(SIGALRM) : rv);
2016 #undef is_ifsws
2017 }
2018
2019 int
c_eval(const char ** wp)2020 c_eval(const char **wp)
2021 {
2022 struct source *s, *saves = source;
2023 int rv;
2024
2025 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2026 return (1);
2027 s = pushs(SWORDS, ATEMP);
2028 s->u.strv = wp + builtin_opt.optind;
2029 s->line = current_lineno;
2030
2031 /*-
2032 * The following code handles the case where the command is
2033 * empty due to failed command substitution, for example by
2034 * eval "$(false)"
2035 * This has historically returned 1 by AT&T ksh88. In this
2036 * case, shell() will not set or change exstat because the
2037 * compiled tree is empty, so it will use the value we pass
2038 * from subst_exstat, which is cleared in execute(), so it
2039 * should have been 0 if there were no substitutions.
2040 *
2041 * POSIX however says we don't do this, even though it is
2042 * traditionally done. AT&T ksh93 agrees with POSIX, so we
2043 * do. The following is an excerpt from SUSv4 [1003.2-2008]:
2044 *
2045 * 2.9.1: Simple Commands
2046 * ... If there is a command name, execution shall
2047 * continue as described in 2.9.1.1 [Command Search
2048 * and Execution]. If there is no command name, but
2049 * the command contained a command substitution, the
2050 * command shall complete with the exit status of the
2051 * last command substitution performed.
2052 * 2.9.1.1: Command Search and Execution
2053 * (1) a. If the command name matches the name of a
2054 * special built-in utility, that special built-in
2055 * utility shall be invoked.
2056 * 2.14.5: eval
2057 * If there are no arguments, or only null arguments,
2058 * eval shall return a zero exit status; ...
2059 */
2060 /* AT&T ksh88: use subst_exstat */
2061 /* exstat = subst_exstat; */
2062 /* SUSv4: OR with a high value never written otherwise */
2063 exstat |= 0x4000;
2064
2065 rv = shell(s, 2);
2066 source = saves;
2067 afree(s, ATEMP);
2068 if (exstat & 0x4000)
2069 /* detect old exstat, use 0 in that case */
2070 rv = 0;
2071 return (rv);
2072 }
2073
2074 int
c_trap(const char ** wp)2075 c_trap(const char **wp)
2076 {
2077 Trap *p = sigtraps;
2078 int i = ksh_NSIG;
2079 const char *s;
2080
2081 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2082 return (1);
2083 wp += builtin_opt.optind;
2084
2085 if (*wp == NULL) {
2086 do {
2087 if (p->trap) {
2088 shf_puts("trap -- ", shl_stdout);
2089 print_value_quoted(shl_stdout, p->trap);
2090 shprintf(Tf__sN, p->name);
2091 }
2092 ++p;
2093 } while (i--);
2094 return (0);
2095 }
2096
2097 if (getn(*wp, &i)) {
2098 /* first argument is a signal number, reset them all */
2099 s = NULL;
2100 } else {
2101 /* first argument must be a command, then */
2102 s = *wp++;
2103 /* reset traps? */
2104 if (ksh_isdash(s))
2105 s = NULL;
2106 }
2107
2108 /* set/clear the traps */
2109 i = 0;
2110 while (*wp)
2111 if (!(p = gettrap(*wp++, true, true))) {
2112 warningf(true, Tbad_sig_ss, builtin_argv0, wp[-1]);
2113 i = 1;
2114 } else
2115 settrap(p, s);
2116 return (i);
2117 }
2118
2119 int
c_exitreturn(const char ** wp)2120 c_exitreturn(const char **wp)
2121 {
2122 int n, how = LEXIT;
2123
2124 if (wp[1]) {
2125 if (wp[2])
2126 goto c_exitreturn_err;
2127 exstat = bi_getn(wp[1], &n) ? (n & 0xFF) : 1;
2128 } else if (trap_exstat != -1)
2129 exstat = trap_exstat;
2130
2131 if (wp[0][0] == 'r') {
2132 /* return */
2133 struct env *ep;
2134
2135 /*
2136 * need to tell if this is exit or return so trap exit will
2137 * work right (POSIX)
2138 */
2139 for (ep = e; ep; ep = ep->oenv)
2140 if (STOP_RETURN(ep->type)) {
2141 how = LRETURN;
2142 break;
2143 }
2144 }
2145
2146 if (how == LEXIT && !really_exit && j_stopped_running()) {
2147 really_exit = true;
2148 how = LSHELL;
2149 }
2150
2151 /* get rid of any I/O redirections */
2152 quitenv(NULL);
2153 unwind(how);
2154 /* NOTREACHED */
2155
2156 c_exitreturn_err:
2157 bi_errorf(Ttoo_many_args);
2158 return (1);
2159 }
2160
2161 int
c_brkcont(const char ** wp)2162 c_brkcont(const char **wp)
2163 {
2164 unsigned int quit;
2165 int n;
2166 struct env *ep, *last_ep = NULL;
2167 const char *arg;
2168
2169 if (ksh_getopt(wp, &builtin_opt, null) == '?')
2170 goto c_brkcont_err;
2171 arg = wp[builtin_opt.optind];
2172
2173 if (!arg)
2174 n = 1;
2175 else if (!bi_getn(arg, &n))
2176 goto c_brkcont_err;
2177 if (n <= 0) {
2178 /* AT&T ksh does this for non-interactive shells only - weird */
2179 bi_errorf("%s: bad value", arg);
2180 goto c_brkcont_err;
2181 }
2182 quit = (unsigned int)n;
2183
2184 /* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
2185 for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
2186 if (ep->type == E_LOOP) {
2187 if (--quit == 0)
2188 break;
2189 ep->flags |= EF_BRKCONT_PASS;
2190 last_ep = ep;
2191 }
2192
2193 if (quit) {
2194 /*
2195 * AT&T ksh doesn't print a message - just does what it
2196 * can. We print a message 'cause it helps in debugging
2197 * scripts, but don't generate an error (ie, keep going).
2198 */
2199 if ((unsigned int)n == quit) {
2200 warningf(true, Tf_cant_s, wp[0], wp[0]);
2201 return (0);
2202 }
2203 /*
2204 * POSIX says if n is too big, the last enclosing loop
2205 * shall be used. Doesn't say to print an error but we
2206 * do anyway 'cause the user messed up.
2207 */
2208 if (last_ep)
2209 last_ep->flags &= ~EF_BRKCONT_PASS;
2210 warningf(true, "%s: can only %s %u level(s)",
2211 wp[0], wp[0], (unsigned int)n - quit);
2212 }
2213
2214 unwind(*wp[0] == 'b' ? LBREAK : LCONTIN);
2215 /* NOTREACHED */
2216
2217 c_brkcont_err:
2218 return (1);
2219 }
2220
2221 int
c_set(const char ** wp)2222 c_set(const char **wp)
2223 {
2224 int argi;
2225 bool setargs;
2226 struct block *l = e->loc;
2227
2228 if ((l->flags & BF_RESETSPEC)) {
2229 /* prevent pollution */
2230 l->flags &= ~BF_RESETSPEC;
2231 /* operate on parent environment */
2232 l = l->next;
2233 }
2234
2235 if (wp[1] == NULL) {
2236 static const char *args[] = { Tset, "-", NULL };
2237 return (c_typeset(args));
2238 }
2239
2240 if ((argi = parse_args(wp, OF_SET, &setargs)) < 0)
2241 return (2);
2242 /* set $# and $* */
2243 if (setargs) {
2244 const char **owp;
2245
2246 wp += argi - 1;
2247 owp = wp;
2248 /* save $0 */
2249 wp[0] = l->argv[0];
2250 while (*++wp != NULL)
2251 strdupx(*wp, *wp, &l->area);
2252 l->argc = wp - owp - 1;
2253 l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
2254 for (wp = l->argv; (*wp++ = *owp++) != NULL; )
2255 ;
2256 }
2257 /*-
2258 * POSIX says set exit status is 0, but old scripts that use
2259 * getopt(1) use the construct
2260 * set -- $(getopt ab:c "$@")
2261 * which assumes the exit value set will be that of the $()
2262 * (subst_exstat is cleared in execute() so that it will be 0
2263 * if there are no command substitutions).
2264 */
2265 #ifdef MKSH_LEGACY_MODE
2266 /* traditional behaviour, unless set -o posix */
2267 return (Flag(FPOSIX) ? 0 : subst_exstat);
2268 #else
2269 /* conformant behaviour, unless set -o sh +o posix */
2270 return (Flag(FSH) && !Flag(FPOSIX) ? subst_exstat : 0);
2271 #endif
2272 }
2273
2274 int
c_unset(const char ** wp)2275 c_unset(const char **wp)
2276 {
2277 const char *id;
2278 int optc, rv = 0;
2279 bool unset_var = true;
2280
2281 while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
2282 switch (optc) {
2283 case 'f':
2284 unset_var = false;
2285 break;
2286 case 'v':
2287 unset_var = true;
2288 break;
2289 case '?':
2290 /*XXX not reached due to GF_ERROR */
2291 return (2);
2292 }
2293 wp += builtin_opt.optind;
2294 for (; (id = *wp) != NULL; wp++)
2295 if (unset_var) {
2296 /* unset variable */
2297 struct tbl *vp;
2298 char *cp = NULL;
2299 size_t n;
2300
2301 n = strlen(id);
2302 if (n > 3 && ord(id[n - 3]) == ORD('[') &&
2303 ord(id[n - 2]) == ORD('*') &&
2304 ord(id[n - 1]) == ORD(']')) {
2305 strndupx(cp, id, n - 3, ATEMP);
2306 id = cp;
2307 optc = 3;
2308 } else
2309 optc = vstrchr(id, '[') ? 0 : 1;
2310
2311 vp = global(id);
2312 afree(cp, ATEMP);
2313
2314 if ((vp->flag&RDONLY)) {
2315 warningf(true, Tf_ro, vp->name);
2316 rv = 1;
2317 } else
2318 unset(vp, optc);
2319 } else
2320 /* unset function */
2321 define(id, NULL);
2322 return (rv);
2323 }
2324
2325 static void
p_time(struct shf * shf,bool posix,long tv_sec,int tv_usec,int width,const char * prefix,const char * suffix)2326 p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
2327 const char *prefix, const char *suffix)
2328 {
2329 tv_usec /= 10000;
2330 if (posix)
2331 shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
2332 tv_sec, tv_usec, suffix);
2333 else
2334 shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
2335 tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
2336 }
2337
2338 int
c_times(const char ** wp MKSH_A_UNUSED)2339 c_times(const char **wp MKSH_A_UNUSED)
2340 {
2341 struct rusage usage;
2342
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");
2348
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");
2354
2355 return (0);
2356 }
2357
2358 /*
2359 * time pipeline (really a statement, not a built-in command)
2360 */
2361 int
timex(struct op * t,int f,volatile int * xerrok)2362 timex(struct op *t, int f, volatile int *xerrok)
2363 {
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 */
2367 int rv = 0, tf = 0;
2368 struct rusage ru0, ru1, cru0, cru1;
2369 struct timeval usrtime, systime, tv0, tv1;
2370
2371 mksh_TIME(tv0);
2372 getrusage(RUSAGE_SELF, &ru0);
2373 getrusage(RUSAGE_CHILDREN, &cru0);
2374 if (t->left) {
2375 /*
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).
2382 */
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];
2388 mksh_TIME(tv1);
2389 getrusage(RUSAGE_SELF, &ru1);
2390 getrusage(RUSAGE_CHILDREN, &cru1);
2391 } else
2392 tf = TF_NOARGS;
2393
2394 if (tf & TF_NOARGS) {
2395 /* ksh93 - report shell times (shell+kids) */
2396 tf |= TF_NOREAL;
2397 timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
2398 timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
2399 } else {
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);
2404 }
2405
2406 if (!(tf & TF_NOREAL)) {
2407 timersub(&tv1, &tv0, &tv1);
2408 if (tf & TF_POSIX)
2409 p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
2410 5, Treal_sp1, "\n");
2411 else
2412 p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
2413 5, null, Treal_sp2);
2414 }
2415 if (tf & TF_POSIX)
2416 p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
2417 5, Tuser_sp1, "\n");
2418 else
2419 p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
2420 5, null, Tuser_sp2);
2421 if (tf & TF_POSIX)
2422 p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
2423 5, "sys ", "\n");
2424 else
2425 p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
2426 5, null, " system\n");
2427 shf_flush(shl_out);
2428
2429 return (rv);
2430 }
2431
2432 void
timex_hook(struct op * t,char ** volatile * app)2433 timex_hook(struct op *t, char **volatile *app)
2434 {
2435 char **wp = *app;
2436 int optc, i, j;
2437 Getopt opt;
2438
2439 ksh_getopt_reset(&opt, 0);
2440 /* start at the start */
2441 opt.optind = 0;
2442 while ((optc = ksh_getopt((const char **)wp, &opt, ":p")) != -1)
2443 switch (optc) {
2444 case 'p':
2445 t->str[0] |= TF_POSIX;
2446 break;
2447 case '?':
2448 errorf(Tf_optfoo, Ttime, Tcolsp,
2449 opt.optarg[0], Tunknown_option);
2450 case ':':
2451 errorf(Tf_optfoo, Ttime, Tcolsp,
2452 opt.optarg[0], Treq_arg);
2453 }
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++)
2459 ;
2460 }
2461 if (!wp[0])
2462 t->str[0] |= TF_NOARGS;
2463 *app = wp;
2464 }
2465
2466 /* exec with no args - args case is taken care of in comexec() */
2467 int
c_exec(const char ** wp MKSH_A_UNUSED)2468 c_exec(const char **wp MKSH_A_UNUSED)
2469 {
2470 int i;
2471
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]);
2477 /*
2478 * keep all file descriptors > 2 private for ksh,
2479 * but not for POSIX or legacy/kludge sh
2480 */
2481 if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
2482 e->savefd[i])
2483 fcntl(i, F_SETFD, FD_CLOEXEC);
2484 }
2485 e->savefd = NULL;
2486 }
2487 return (0);
2488 }
2489
2490 #if HAVE_MKNOD && !defined(__OS2__)
2491 int
c_mknod(const char ** wp)2492 c_mknod(const char **wp)
2493 {
2494 int argc, optc, rv = 0;
2495 bool ismkfifo = false;
2496 const char **argv;
2497 void *set = NULL;
2498 mode_t mode = 0, oldmode = 0;
2499
2500 while ((optc = ksh_getopt(wp, &builtin_opt, "m:")) != -1) {
2501 switch (optc) {
2502 case 'm':
2503 set = setmode(builtin_opt.optarg);
2504 if (set == NULL) {
2505 bi_errorf("invalid file mode");
2506 return (1);
2507 }
2508 mode = getmode(set, (mode_t)(DEFFILEMODE));
2509 free_ossetmode(set);
2510 break;
2511 default:
2512 goto c_mknod_usage;
2513 }
2514 }
2515 argv = &wp[builtin_opt.optind];
2516 if (argv[0] == NULL)
2517 goto c_mknod_usage;
2518 for (argc = 0; argv[argc]; argc++)
2519 ;
2520 if (argc == 2 && argv[1][0] == 'p')
2521 ismkfifo = true;
2522 else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
2523 goto c_mknod_usage;
2524
2525 if (set != NULL)
2526 oldmode = umask((mode_t)0);
2527 else
2528 mode = DEFFILEMODE;
2529
2530 mode |= (argv[1][0] == 'b') ? S_IFBLK :
2531 (argv[1][0] == 'c') ? S_IFCHR : 0;
2532
2533 if (!ismkfifo) {
2534 unsigned long majnum, minnum;
2535 dev_t dv;
2536 char *c;
2537
2538 majnum = strtoul(argv[2], &c, 0);
2539 if ((c == argv[2]) || (*c != '\0')) {
2540 bi_errorf(Tf_nonnum, "device", "major", argv[2]);
2541 goto c_mknod_err;
2542 }
2543 minnum = strtoul(argv[3], &c, 0);
2544 if ((c == argv[3]) || (*c != '\0')) {
2545 bi_errorf(Tf_nonnum, "device", "minor", argv[3]);
2546 goto c_mknod_err;
2547 }
2548 dv = makedev(majnum, minnum);
2549 if ((unsigned long)(major(dv)) != majnum) {
2550 bi_errorf(Tf_toolarge, "device", "major", majnum);
2551 goto c_mknod_err;
2552 }
2553 if ((unsigned long)(minor(dv)) != minnum) {
2554 bi_errorf(Tf_toolarge, "device", "minor", minnum);
2555 goto c_mknod_err;
2556 }
2557 if (mknod(argv[0], mode, dv))
2558 goto c_mknod_failed;
2559 } else if (mkfifo(argv[0], mode)) {
2560 c_mknod_failed:
2561 bi_errorf(Tf_sD_s, argv[0], cstrerror(errno));
2562 c_mknod_err:
2563 rv = 1;
2564 }
2565
2566 if (set)
2567 umask(oldmode);
2568 return (rv);
2569 c_mknod_usage:
2570 bi_errorf("usage: mknod [-m mode] name %s", "b|c major minor");
2571 bi_errorf("usage: mknod [-m mode] name %s", "p");
2572 return (1);
2573 }
2574 #endif
2575
2576 /*-
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
2583 * | operand
2584 * | "(" oexpr ")"
2585 * ;
2586 *
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";
2590 *
2591 * binary-operator ::= "="|"=="|"!="|"<"|">"|"-eq"|"-ne"|"-gt"|"-ge"|
2592 * "-lt"|"-le"|"-ef"|"-nt"|"-ot";
2593 *
2594 * operand ::= <anything>
2595 */
2596
2597 /* POSIX says > 1 for errors */
2598 #define T_ERR_EXIT 2
2599
2600 int
c_test(const char ** wp)2601 c_test(const char **wp)
2602 {
2603 int argc, rv, invert = 0;
2604 Test_env te;
2605 Test_op op;
2606 Test_meta tm;
2607 const char *lhs, **swp;
2608
2609 te.flags = 0;
2610 te.isa = ptest_isa;
2611 te.getopnd = ptest_getopnd;
2612 te.eval = test_eval;
2613 te.error = ptest_error;
2614
2615 for (argc = 0; wp[argc]; argc++)
2616 ;
2617
2618 if (strcmp(wp[0], Tbracket) == 0) {
2619 if (strcmp(wp[--argc], "]") != 0) {
2620 bi_errorf("missing ]");
2621 return (T_ERR_EXIT);
2622 }
2623 }
2624
2625 te.pos.wp = wp + 1;
2626 te.wp_end = wp + argc;
2627
2628 /*
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)()'.
2633 */
2634 switch (argc - 1) {
2635 case 0:
2636 return (1);
2637 case 1:
2638 ptest_one:
2639 op = TO_STNZE;
2640 goto ptest_unary;
2641 case 2:
2642 ptest_two:
2643 if (ptest_isa(&te, TM_NOT)) {
2644 ++invert;
2645 goto ptest_one;
2646 }
2647 if ((op = ptest_isa(&te, TM_UNOP))) {
2648 ptest_unary:
2649 rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
2650 ptest_out:
2651 if (te.flags & TEF_ERROR)
2652 return (T_ERR_EXIT);
2653 return ((invert & 1) ? rv : !rv);
2654 }
2655 /* let the parser deal with anything else */
2656 break;
2657 case 3:
2658 ptest_three:
2659 swp = te.pos.wp;
2660 /* use inside knowledge of ptest_getopnd inlined below */
2661 lhs = *te.pos.wp++;
2662 if ((op = ptest_isa(&te, TM_BINOP))) {
2663 /* test lhs op rhs */
2664 rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
2665 goto ptest_out;
2666 }
2667 if (ptest_isa(&te, tm = TM_AND) || ptest_isa(&te, tm = TM_OR)) {
2668 /* XSI */
2669 argc = test_eval(&te, TO_STNZE, lhs, NULL, true);
2670 rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, true);
2671 if (tm == TM_AND)
2672 rv = argc && rv;
2673 else
2674 rv = argc || rv;
2675 goto ptest_out;
2676 }
2677 /* back up to lhs */
2678 te.pos.wp = swp;
2679 if (ptest_isa(&te, TM_NOT)) {
2680 ++invert;
2681 goto ptest_two;
2682 }
2683 if (ptest_isa(&te, TM_OPAREN)) {
2684 swp = te.pos.wp;
2685 /* skip operand, without evaluation */
2686 te.pos.wp++;
2687 /* check for closing parenthesis */
2688 op = ptest_isa(&te, TM_CPAREN);
2689 /* back up to operand */
2690 te.pos.wp = swp;
2691 /* if there was a closing paren, handle it */
2692 if (op)
2693 goto ptest_one;
2694 /* backing up is done before calling the parser */
2695 }
2696 /* let the parser deal with it */
2697 break;
2698 case 4:
2699 if (ptest_isa(&te, TM_NOT)) {
2700 ++invert;
2701 goto ptest_three;
2702 }
2703 if (ptest_isa(&te, TM_OPAREN)) {
2704 swp = te.pos.wp;
2705 /* skip two operands, without evaluation */
2706 te.pos.wp++;
2707 te.pos.wp++;
2708 /* check for closing parenthesis */
2709 op = ptest_isa(&te, TM_CPAREN);
2710 /* back up to first operand */
2711 te.pos.wp = swp;
2712 /* if there was a closing paren, handle it */
2713 if (op)
2714 goto ptest_two;
2715 /* backing up is done before calling the parser */
2716 }
2717 /* defer this to the parser */
2718 break;
2719 }
2720
2721 /* "The results are unspecified." */
2722 te.pos.wp = wp + 1;
2723 return (test_parse(&te));
2724 }
2725
2726 /*
2727 * Generic test routines.
2728 */
2729
2730 Test_op
test_isop(Test_meta meta,const char * s)2731 test_isop(Test_meta meta, const char *s)
2732 {
2733 char sc1;
2734 const struct t_op *tbl;
2735
2736 tbl = meta == TM_UNOP ? u_ops : b_ops;
2737 if (*s) {
2738 sc1 = s[1];
2739 for (; tbl->op_text[0]; tbl++)
2740 if (sc1 == tbl->op_text[1] && !strcmp(s, tbl->op_text))
2741 return (tbl->op_num);
2742 }
2743 return (TO_NONOP);
2744 }
2745
2746 #ifdef __OS2__
2747 #define test_access(name,mode) access_ex(access, (name), (mode))
2748 #define test_stat(name,buffer) stat_ex(stat, (name), (buffer))
2749 #define test_lstat(name,buffer) stat_ex(lstat, (name), (buffer))
2750 #else
2751 #define test_access(name,mode) access((name), (mode))
2752 #define test_stat(name,buffer) stat((name), (buffer))
2753 #define test_lstat(name,buffer) lstat((name), (buffer))
2754 #endif
2755
2756 #if HAVE_ST_MTIM
2757 #undef st_mtimensec
2758 #define st_mtimensec st_mtim.tv_nsec
2759 #endif
2760
2761 static int
mtimecmp(const struct stat * sb1,const struct stat * sb2)2762 mtimecmp(const struct stat *sb1, const struct stat *sb2)
2763 {
2764 if (sb1->st_mtime < sb2->st_mtime)
2765 return (-1);
2766 if (sb1->st_mtime > sb2->st_mtime)
2767 return (1);
2768 #if (HAVE_ST_MTIMENSEC || HAVE_ST_MTIM)
2769 if (sb1->st_mtimensec < sb2->st_mtimensec)
2770 return (-1);
2771 if (sb1->st_mtimensec > sb2->st_mtimensec)
2772 return (1);
2773 #endif
2774 return (0);
2775 }
2776
2777 int
test_eval(Test_env * te,Test_op op,const char * opnd1,const char * opnd2,bool do_eval)2778 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
2779 bool do_eval)
2780 {
2781 int i, s;
2782 size_t k;
2783 struct stat b1, b2;
2784 mksh_ari_t v1, v2;
2785 struct tbl *vp;
2786
2787 if (!do_eval)
2788 return (0);
2789
2790 #ifdef DEBUG
2791 switch (op) {
2792 /* Binary operators */
2793 case TO_STEQL:
2794 case TO_STNEQ:
2795 case TO_STLT:
2796 case TO_STGT:
2797 case TO_INTEQ:
2798 case TO_INTNE:
2799 case TO_INTGT:
2800 case TO_INTGE:
2801 case TO_INTLT:
2802 case TO_INTLE:
2803 case TO_FILEQ:
2804 case TO_FILNT:
2805 case TO_FILOT:
2806 /* consistency check, but does not happen in practice */
2807 if (!opnd2) {
2808 te->flags |= TEF_ERROR;
2809 return (1);
2810 }
2811 break;
2812 default:
2813 /* for completeness of switch */
2814 break;
2815 }
2816 #endif
2817
2818 switch (op) {
2819
2820 /*
2821 * Unary Operators
2822 */
2823
2824 /* -n */
2825 case TO_STNZE:
2826 return (*opnd1 != '\0');
2827
2828 /* -z */
2829 case TO_STZER:
2830 return (*opnd1 == '\0');
2831
2832 /* -v */
2833 case TO_ISSET:
2834 return ((vp = isglobal(opnd1, false)) && (vp->flag & ISSET));
2835
2836 /* -o */
2837 case TO_OPTION:
2838 if ((i = *opnd1) == '!' || i == '?')
2839 opnd1++;
2840 if ((k = option(opnd1)) == (size_t)-1)
2841 return (0);
2842 return (i == '?' ? 1 : i == '!' ? !Flag(k) : Flag(k));
2843
2844 /* -r */
2845 case TO_FILRD:
2846 /* LINTED use of access */
2847 return (test_access(opnd1, R_OK) == 0);
2848
2849 /* -w */
2850 case TO_FILWR:
2851 /* LINTED use of access */
2852 return (test_access(opnd1, W_OK) == 0);
2853
2854 /* -x */
2855 case TO_FILEX:
2856 return (ksh_access(opnd1, X_OK) == 0);
2857
2858 /* -a */
2859 case TO_FILAXST:
2860 /* -e */
2861 case TO_FILEXST:
2862 return (test_stat(opnd1, &b1) == 0);
2863
2864 /* -f */
2865 case TO_FILREG:
2866 return (test_stat(opnd1, &b1) == 0 && S_ISREG(b1.st_mode));
2867
2868 /* -d */
2869 case TO_FILID:
2870 return (test_stat(opnd1, &b1) == 0 && S_ISDIR(b1.st_mode));
2871
2872 /* -c */
2873 case TO_FILCDEV:
2874 return (test_stat(opnd1, &b1) == 0 && S_ISCHR(b1.st_mode));
2875
2876 /* -b */
2877 case TO_FILBDEV:
2878 return (test_stat(opnd1, &b1) == 0 && S_ISBLK(b1.st_mode));
2879
2880 /* -p */
2881 case TO_FILFIFO:
2882 return (test_stat(opnd1, &b1) == 0 && S_ISFIFO(b1.st_mode));
2883
2884 /* -h or -L */
2885 case TO_FILSYM:
2886 #ifdef MKSH__NO_SYMLINK
2887 return (0);
2888 #else
2889 return (test_lstat(opnd1, &b1) == 0 && S_ISLNK(b1.st_mode));
2890 #endif
2891
2892 /* -S */
2893 case TO_FILSOCK:
2894 return (test_stat(opnd1, &b1) == 0 && S_ISSOCK(b1.st_mode));
2895
2896 /* -H => HP context dependent files (directories) */
2897 case TO_FILCDF:
2898 #ifdef S_ISCDF
2899 {
2900 char *nv;
2901
2902 /*
2903 * Append a + to filename and check to see if result is
2904 * a setuid directory. CDF stuff in general is hookey,
2905 * since it breaks for, e.g., the following sequence:
2906 * echo hi >foo+; mkdir foo; echo bye >foo/default;
2907 * chmod u+s foo (foo+ refers to the file with hi in it,
2908 * there is no way to get at the file with bye in it;
2909 * please correct me if I'm wrong about this).
2910 */
2911
2912 nv = shf_smprintf("%s+", opnd1);
2913 i = (test_stat(nv, &b1) == 0 && S_ISCDF(b1.st_mode));
2914 afree(nv, ATEMP);
2915 return (i);
2916 }
2917 #else
2918 return (0);
2919 #endif
2920
2921 /* -u */
2922 case TO_FILSETU:
2923 return (test_stat(opnd1, &b1) == 0 &&
2924 (b1.st_mode & S_ISUID) == S_ISUID);
2925
2926 /* -g */
2927 case TO_FILSETG:
2928 return (test_stat(opnd1, &b1) == 0 &&
2929 (b1.st_mode & S_ISGID) == S_ISGID);
2930
2931 /* -k */
2932 case TO_FILSTCK:
2933 #ifdef S_ISVTX
2934 return (test_stat(opnd1, &b1) == 0 &&
2935 (b1.st_mode & S_ISVTX) == S_ISVTX);
2936 #else
2937 return (0);
2938 #endif
2939
2940 /* -s */
2941 case TO_FILGZ:
2942 return (test_stat(opnd1, &b1) == 0 &&
2943 (off_t)b1.st_size > (off_t)0);
2944
2945 /* -t */
2946 case TO_FILTT:
2947 if (opnd1 && !bi_getn(opnd1, &i)) {
2948 te->flags |= TEF_ERROR;
2949 i = 0;
2950 } else
2951 i = isatty(opnd1 ? i : 0);
2952 return (i);
2953
2954 /* -O */
2955 case TO_FILUID:
2956 return (test_stat(opnd1, &b1) == 0 &&
2957 (uid_t)b1.st_uid == ksheuid);
2958
2959 /* -G */
2960 case TO_FILGID:
2961 return (test_stat(opnd1, &b1) == 0 &&
2962 (gid_t)b1.st_gid == kshegid);
2963
2964 /*
2965 * Binary Operators
2966 */
2967
2968 /* =, == */
2969 case TO_STEQL:
2970 if (te->flags & TEF_DBRACKET) {
2971 if ((i = gmatchx(opnd1, opnd2, false)))
2972 record_match(opnd1);
2973 return (i);
2974 }
2975 return (strcmp(opnd1, opnd2) == 0);
2976
2977 /* != */
2978 case TO_STNEQ:
2979 if (te->flags & TEF_DBRACKET) {
2980 if ((i = gmatchx(opnd1, opnd2, false)))
2981 record_match(opnd1);
2982 return (!i);
2983 }
2984 return (strcmp(opnd1, opnd2) != 0);
2985
2986 /* < */
2987 case TO_STLT:
2988 return (strcmp(opnd1, opnd2) < 0);
2989
2990 /* > */
2991 case TO_STGT:
2992 return (strcmp(opnd1, opnd2) > 0);
2993
2994 /* -nt */
2995 case TO_FILNT:
2996 /*
2997 * ksh88/ksh93 succeed if file2 can't be stated
2998 * (subtly different from 'does not exist').
2999 */
3000 return (test_stat(opnd1, &b1) == 0 &&
3001 (((s = test_stat(opnd2, &b2)) == 0 &&
3002 mtimecmp(&b1, &b2) > 0) || s < 0));
3003
3004 /* -ot */
3005 case TO_FILOT:
3006 /*
3007 * ksh88/ksh93 succeed if file1 can't be stated
3008 * (subtly different from 'does not exist').
3009 */
3010 return (test_stat(opnd2, &b2) == 0 &&
3011 (((s = test_stat(opnd1, &b1)) == 0 &&
3012 mtimecmp(&b1, &b2) < 0) || s < 0));
3013
3014 /* -ef */
3015 case TO_FILEQ:
3016 return (test_stat(opnd1, &b1) == 0 &&
3017 test_stat(opnd2, &b2) == 0 &&
3018 b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino);
3019
3020 /* all other cases */
3021 case TO_NONOP:
3022 case TO_NONNULL:
3023 /* throw the error */
3024 break;
3025
3026 /* -eq */
3027 case TO_INTEQ:
3028 /* -ne */
3029 case TO_INTNE:
3030 /* -ge */
3031 case TO_INTGE:
3032 /* -gt */
3033 case TO_INTGT:
3034 /* -le */
3035 case TO_INTLE:
3036 /* -lt */
3037 case TO_INTLT:
3038 if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
3039 !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
3040 /* error already printed.. */
3041 te->flags |= TEF_ERROR;
3042 return (1);
3043 }
3044 switch (op) {
3045 case TO_INTEQ:
3046 return (v1 == v2);
3047 case TO_INTNE:
3048 return (v1 != v2);
3049 case TO_INTGE:
3050 return (v1 >= v2);
3051 case TO_INTGT:
3052 return (v1 > v2);
3053 case TO_INTLE:
3054 return (v1 <= v2);
3055 case TO_INTLT:
3056 return (v1 < v2);
3057 default:
3058 /* NOTREACHED */
3059 break;
3060 }
3061 /* NOTREACHED */
3062 }
3063 (*te->error)(te, 0, "internal error: unknown op");
3064 return (1);
3065 }
3066
3067 int
test_parse(Test_env * te)3068 test_parse(Test_env *te)
3069 {
3070 int rv;
3071
3072 rv = test_oexpr(te, 1);
3073
3074 if (!(te->flags & TEF_ERROR) && !(*te->isa)(te, TM_END))
3075 (*te->error)(te, 0, "unexpected operator/operand");
3076
3077 return ((te->flags & TEF_ERROR) ? T_ERR_EXIT : !rv);
3078 }
3079
3080 static int
test_oexpr(Test_env * te,bool do_eval)3081 test_oexpr(Test_env *te, bool do_eval)
3082 {
3083 int rv;
3084
3085 if ((rv = test_aexpr(te, do_eval)))
3086 do_eval = false;
3087 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
3088 return (test_oexpr(te, do_eval) || rv);
3089 return (rv);
3090 }
3091
3092 static int
test_aexpr(Test_env * te,bool do_eval)3093 test_aexpr(Test_env *te, bool do_eval)
3094 {
3095 int rv;
3096
3097 if (!(rv = test_nexpr(te, do_eval)))
3098 do_eval = false;
3099 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
3100 return (test_aexpr(te, do_eval) && rv);
3101 return (rv);
3102 }
3103
3104 static int
test_nexpr(Test_env * te,bool do_eval)3105 test_nexpr(Test_env *te, bool do_eval)
3106 {
3107 if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
3108 return (!test_nexpr(te, do_eval));
3109 return (test_primary(te, do_eval));
3110 }
3111
3112 static int
test_primary(Test_env * te,bool do_eval)3113 test_primary(Test_env *te, bool do_eval)
3114 {
3115 const char *opnd1, *opnd2;
3116 int rv;
3117 Test_op op;
3118
3119 if (te->flags & TEF_ERROR)
3120 return (0);
3121 if ((*te->isa)(te, TM_OPAREN)) {
3122 rv = test_oexpr(te, do_eval);
3123 if (te->flags & TEF_ERROR)
3124 return (0);
3125 if (!(*te->isa)(te, TM_CPAREN)) {
3126 (*te->error)(te, 0, "missing )");
3127 return (0);
3128 }
3129 return (rv);
3130 }
3131 /*
3132 * Binary should have precedence over unary in this case
3133 * so that something like test \( -f = -f \) is accepted
3134 */
3135 if ((te->flags & TEF_DBRACKET) || (&te->pos.wp[1] < te->wp_end &&
3136 !test_isop(TM_BINOP, te->pos.wp[1]))) {
3137 if ((op = (*te->isa)(te, TM_UNOP))) {
3138 /* unary expression */
3139 opnd1 = (*te->getopnd)(te, op, do_eval);
3140 if (!opnd1) {
3141 (*te->error)(te, -1, Tno_args);
3142 return (0);
3143 }
3144
3145 return ((*te->eval)(te, op, opnd1, NULL, do_eval));
3146 }
3147 }
3148 opnd1 = (*te->getopnd)(te, TO_NONOP, do_eval);
3149 if (!opnd1) {
3150 (*te->error)(te, 0, "expression expected");
3151 return (0);
3152 }
3153 if ((op = (*te->isa)(te, TM_BINOP))) {
3154 /* binary expression */
3155 opnd2 = (*te->getopnd)(te, op, do_eval);
3156 if (!opnd2) {
3157 (*te->error)(te, -1, "missing second argument");
3158 return (0);
3159 }
3160
3161 return ((*te->eval)(te, op, opnd1, opnd2, do_eval));
3162 }
3163 return ((*te->eval)(te, TO_STNZE, opnd1, NULL, do_eval));
3164 }
3165
3166 /*
3167 * Plain test (test and [ .. ]) specific routines.
3168 */
3169
3170 /*
3171 * Test if the current token is a whatever. Accepts the current token if
3172 * it is. Returns 0 if it is not, non-zero if it is (in the case of
3173 * TM_UNOP and TM_BINOP, the returned value is a Test_op).
3174 */
3175 static Test_op
ptest_isa(Test_env * te,Test_meta meta)3176 ptest_isa(Test_env *te, Test_meta meta)
3177 {
3178 /* Order important - indexed by Test_meta values */
3179 static const char * const tokens[] = {
3180 Tdo, Tda, "!", "(", ")"
3181 };
3182 Test_op rv;
3183
3184 if (te->pos.wp >= te->wp_end)
3185 return (meta == TM_END ? TO_NONNULL : TO_NONOP);
3186
3187 if (meta == TM_UNOP || meta == TM_BINOP)
3188 rv = test_isop(meta, *te->pos.wp);
3189 else if (meta == TM_END)
3190 rv = TO_NONOP;
3191 else
3192 rv = !strcmp(*te->pos.wp, tokens[(int)meta]) ?
3193 TO_NONNULL : TO_NONOP;
3194
3195 /* Accept the token? */
3196 if (rv != TO_NONOP)
3197 te->pos.wp++;
3198
3199 return (rv);
3200 }
3201
3202 static const char *
ptest_getopnd(Test_env * te,Test_op op,bool do_eval MKSH_A_UNUSED)3203 ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
3204 {
3205 if (te->pos.wp >= te->wp_end)
3206 return (op == TO_FILTT ? "1" : NULL);
3207 return (*te->pos.wp++);
3208 }
3209
3210 static void
ptest_error(Test_env * te,int ofs,const char * msg)3211 ptest_error(Test_env *te, int ofs, const char *msg)
3212 {
3213 const char *op;
3214
3215 te->flags |= TEF_ERROR;
3216 if ((op = te->pos.wp + ofs >= te->wp_end ? NULL : te->pos.wp[ofs]))
3217 bi_errorf(Tf_sD_s, op, msg);
3218 else
3219 bi_errorf(Tf_s, msg);
3220 }
3221
3222 #ifndef MKSH_NO_LIMITS
3223 #define SOFT 0x1
3224 #define HARD 0x2
3225
3226 /* Magic to divine the 'm' and 'v' limits */
3227
3228 #ifdef RLIMIT_AS
3229 #if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
3230 !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
3231 #define ULIMIT_V_IS_AS
3232 #elif defined(RLIMIT_VMEM)
3233 #if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
3234 #define ULIMIT_V_IS_AS
3235 #else
3236 #define ULIMIT_V_IS_VMEM
3237 #endif
3238 #endif
3239 #endif
3240
3241 #ifdef RLIMIT_RSS
3242 #ifdef ULIMIT_V_IS_VMEM
3243 #define ULIMIT_M_IS_RSS
3244 #elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
3245 #define ULIMIT_M_IS_VMEM
3246 #else
3247 #define ULIMIT_M_IS_RSS
3248 #endif
3249 #if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)
3250 #undef ULIMIT_M_IS_RSS
3251 #endif
3252 #endif
3253
3254 #if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
3255 #define ULIMIT_V_IS_VMEM
3256 #endif
3257
3258 #if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
3259 (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
3260 #define ULIMIT_M_IS_VMEM
3261 #endif
3262
3263 #if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
3264 (RLIMIT_VMEM == RLIMIT_AS)
3265 #undef ULIMIT_M_IS_VMEM
3266 #endif
3267
3268 #if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
3269 # error nonsensical m ulimit
3270 #endif
3271
3272 #if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
3273 # error nonsensical v ulimit
3274 #endif
3275
3276 struct limits {
3277 /* limit resource */
3278 int resource;
3279 /* multiply by to get rlim_{cur,max} values */
3280 unsigned int factor;
3281 /* getopts char */
3282 char optchar;
3283 /* limit name */
3284 char name[1];
3285 };
3286
3287 #define RLIMITS_DEFNS
3288 #define FN(lname,lid,lfac,lopt) \
3289 static const struct { \
3290 int resource; \
3291 unsigned int factor; \
3292 char optchar; \
3293 char name[sizeof(lname)]; \
3294 } rlimits_ ## lid = { \
3295 lid, lfac, lopt, lname \
3296 };
3297 #include "rlimits.gen"
3298
3299 static void print_ulimit(const struct limits *, int);
3300 static int set_ulimit(const struct limits *, const char *, int);
3301
3302 static const struct limits * const rlimits[] = {
3303 #define RLIMITS_ITEMS
3304 #include "rlimits.gen"
3305 };
3306
3307 static const char rlimits_opts[] =
3308 #define RLIMITS_OPTCS
3309 #include "rlimits.gen"
3310 ;
3311
3312 int
c_ulimit(const char ** wp)3313 c_ulimit(const char **wp)
3314 {
3315 size_t i = 0;
3316 int how = SOFT | HARD, optc, what = 'f';
3317 bool all = false;
3318
3319 while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
3320 switch (optc) {
3321 case 'H':
3322 how = HARD;
3323 break;
3324 case 'S':
3325 how = SOFT;
3326 break;
3327 case 'a':
3328 all = true;
3329 break;
3330 case '?':
3331 bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
3332 return (1);
3333 default:
3334 what = optc;
3335 }
3336
3337 while (i < NELEM(rlimits)) {
3338 if (rlimits[i]->optchar == what)
3339 goto found;
3340 ++i;
3341 }
3342 internal_warningf("ulimit: %c", what);
3343 return (1);
3344 found:
3345 if (wp[builtin_opt.optind]) {
3346 if (all || wp[builtin_opt.optind + 1]) {
3347 bi_errorf(Ttoo_many_args);
3348 return (1);
3349 }
3350 return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
3351 }
3352 if (!all)
3353 print_ulimit(rlimits[i], how);
3354 else for (i = 0; i < NELEM(rlimits); ++i) {
3355 shprintf("-%c: %-20s ", rlimits[i]->optchar, rlimits[i]->name);
3356 print_ulimit(rlimits[i], how);
3357 }
3358 return (0);
3359 }
3360
3361 static int
set_ulimit(const struct limits * l,const char * v,int how)3362 set_ulimit(const struct limits *l, const char *v, int how)
3363 {
3364 rlim_t val = (rlim_t)0;
3365 struct rlimit limit;
3366
3367 if (strcmp(v, "unlimited") == 0)
3368 val = (rlim_t)RLIM_INFINITY;
3369 else {
3370 mksh_uari_t rval;
3371
3372 if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
3373 return (1);
3374 /*
3375 * Avoid problems caused by typos that evaluate misses due
3376 * to evaluating unset parameters to 0...
3377 * If this causes problems, will have to add parameter to
3378 * evaluate() to control if unset params are 0 or an error.
3379 */
3380 if (!rval && !ctype(v[0], C_DIGIT)) {
3381 bi_errorf("invalid %s limit: %s", l->name, v);
3382 return (1);
3383 }
3384 val = (rlim_t)((rlim_t)rval * l->factor);
3385 }
3386
3387 if (getrlimit(l->resource, &limit) < 0) {
3388 #ifndef MKSH_SMALL
3389 bi_errorf("limit %s could not be read, contact the mksh developers: %s",
3390 l->name, cstrerror(errno));
3391 #endif
3392 /* some can't be read */
3393 limit.rlim_cur = RLIM_INFINITY;
3394 limit.rlim_max = RLIM_INFINITY;
3395 }
3396 if (how & SOFT)
3397 limit.rlim_cur = val;
3398 if (how & HARD)
3399 limit.rlim_max = val;
3400 if (!setrlimit(l->resource, &limit))
3401 return (0);
3402 if (errno == EPERM)
3403 bi_errorf("%s exceeds allowable %s limit", v, l->name);
3404 else
3405 bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
3406 return (1);
3407 }
3408
3409 static void
print_ulimit(const struct limits * l,int how)3410 print_ulimit(const struct limits *l, int how)
3411 {
3412 rlim_t val = (rlim_t)0;
3413 struct rlimit limit;
3414
3415 if (getrlimit(l->resource, &limit)) {
3416 shf_puts("unknown\n", shl_stdout);
3417 return;
3418 }
3419 if (how & SOFT)
3420 val = limit.rlim_cur;
3421 else if (how & HARD)
3422 val = limit.rlim_max;
3423 if (val == (rlim_t)RLIM_INFINITY)
3424 shf_puts("unlimited\n", shl_stdout);
3425 else
3426 shprintf("%lu\n", (unsigned long)(val / l->factor));
3427 }
3428 #endif
3429
3430 int
c_rename(const char ** wp)3431 c_rename(const char **wp)
3432 {
3433 int rv = 1;
3434
3435 /* skip argv[0] */
3436 ++wp;
3437 if (wp[0] && !strcmp(wp[0], "--"))
3438 /* skip "--" (options separator) */
3439 ++wp;
3440
3441 /* check for exactly two arguments */
3442 if (wp[0] == NULL /* first argument */ ||
3443 wp[1] == NULL /* second argument */ ||
3444 wp[2] != NULL /* no further args please */)
3445 bi_errorf(Tsynerr);
3446 else if ((rv = rename(wp[0], wp[1])) != 0) {
3447 rv = errno;
3448 bi_errorf(Tf_sD_s, "failed", cstrerror(rv));
3449 }
3450
3451 return (rv);
3452 }
3453
3454 int
c_realpath(const char ** wp)3455 c_realpath(const char **wp)
3456 {
3457 int rv = 1;
3458 char *buf;
3459
3460 /* skip argv[0] */
3461 ++wp;
3462 if (wp[0] && !strcmp(wp[0], "--"))
3463 /* skip "--" (options separator) */
3464 ++wp;
3465
3466 /* check for exactly one argument */
3467 if (wp[0] == NULL || wp[1] != NULL)
3468 bi_errorf(Tsynerr);
3469 else if ((buf = do_realpath(wp[0])) == NULL) {
3470 rv = errno;
3471 bi_errorf(Tf_sD_s, wp[0], cstrerror(rv));
3472 if ((unsigned int)rv > 255)
3473 rv = 255;
3474 } else {
3475 shprintf(Tf_sN, buf);
3476 afree(buf, ATEMP);
3477 rv = 0;
3478 }
3479
3480 return (rv);
3481 }
3482
3483 int
c_cat(const char ** wp)3484 c_cat(const char **wp)
3485 {
3486 int fd = STDIN_FILENO, rv;
3487 ssize_t n, w;
3488 const char *fn = "<stdin>";
3489 char *buf, *cp;
3490 bool opipe;
3491 #define MKSH_CAT_BUFSIZ 4096
3492
3493 /* parse options: POSIX demands we support "-u" as no-op */
3494 while ((rv = ksh_getopt(wp, &builtin_opt, Tu)) != -1) {
3495 switch (rv) {
3496 case 'u':
3497 /* we already operate unbuffered */
3498 break;
3499 default:
3500 bi_errorf(Tsynerr);
3501 return (1);
3502 }
3503 }
3504 wp += builtin_opt.optind;
3505 rv = 0;
3506
3507 if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
3508 bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
3509 return (1);
3510 }
3511
3512 /* catch SIGPIPE */
3513 opipe = block_pipe();
3514
3515 do {
3516 if (*wp) {
3517 fn = *wp++;
3518 if (ksh_isdash(fn))
3519 fd = STDIN_FILENO;
3520 else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
3521 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3522 rv = 1;
3523 continue;
3524 }
3525 }
3526 while (/* CONSTCOND */ 1) {
3527 if ((n = blocking_read(fd, (cp = buf),
3528 MKSH_CAT_BUFSIZ)) == -1) {
3529 if (errno == EINTR) {
3530 if (opipe)
3531 restore_pipe();
3532 /* give the user a chance to ^C out */
3533 intrcheck();
3534 /* interrupted, try again */
3535 opipe = block_pipe();
3536 continue;
3537 }
3538 /* an error occured during reading */
3539 bi_errorf(Tf_sD_s, fn, cstrerror(errno));
3540 rv = 1;
3541 break;
3542 } else if (n == 0)
3543 /* end of file reached */
3544 break;
3545 while (n) {
3546 if (intrsig)
3547 goto has_intrsig;
3548 if ((w = write(STDOUT_FILENO, cp, n)) != -1) {
3549 n -= w;
3550 cp += w;
3551 continue;
3552 }
3553 if (errno == EINTR) {
3554 has_intrsig:
3555 if (opipe)
3556 restore_pipe();
3557 /* give the user a chance to ^C out */
3558 intrcheck();
3559 /* interrupted, try again */
3560 opipe = block_pipe();
3561 continue;
3562 }
3563 if (errno == EPIPE) {
3564 /* fake receiving signal */
3565 rv = ksh_sigmask(SIGPIPE);
3566 } else {
3567 /* an error occured during writing */
3568 bi_errorf(Tf_sD_s, "<stdout>",
3569 cstrerror(errno));
3570 rv = 1;
3571 }
3572 if (fd != STDIN_FILENO)
3573 close(fd);
3574 goto out;
3575 }
3576 }
3577 if (fd != STDIN_FILENO)
3578 close(fd);
3579 } while (*wp);
3580
3581 out:
3582 if (opipe)
3583 restore_pipe();
3584 free_osfunc(buf);
3585 return (rv);
3586 }
3587
3588 #if HAVE_SELECT
3589 int
c_sleep(const char ** wp)3590 c_sleep(const char **wp)
3591 {
3592 struct timeval tv;
3593 int rv = 1;
3594
3595 /* skip argv[0] */
3596 ++wp;
3597 if (wp[0] && !strcmp(wp[0], "--"))
3598 /* skip "--" (options separator) */
3599 ++wp;
3600
3601 if (!wp[0] || wp[1])
3602 bi_errorf(Tsynerr);
3603 else if (parse_usec(wp[0], &tv))
3604 bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno), wp[0]);
3605 else {
3606 #ifndef MKSH_NOPROSPECTOFWORK
3607 sigset_t omask, bmask;
3608
3609 /* block a number of signals from interrupting us, though */
3610 (void)sigemptyset(&bmask);
3611 (void)sigaddset(&bmask, SIGPIPE);
3612 (void)sigaddset(&bmask, SIGCHLD);
3613 #ifdef SIGWINCH
3614 (void)sigaddset(&bmask, SIGWINCH);
3615 #endif
3616 #ifdef SIGINFO
3617 (void)sigaddset(&bmask, SIGINFO);
3618 #endif
3619 #ifdef SIGUSR1
3620 (void)sigaddset(&bmask, SIGUSR1);
3621 #endif
3622 #ifdef SIGUSR2
3623 (void)sigaddset(&bmask, SIGUSR2);
3624 #endif
3625 sigprocmask(SIG_BLOCK, &bmask, &omask);
3626 #endif
3627 if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
3628 /*
3629 * strictly speaking only for SIGALRM, but the
3630 * execution may be interrupted by other signals
3631 */
3632 rv = 0;
3633 else
3634 bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
3635 #ifndef MKSH_NOPROSPECTOFWORK
3636 /* this will re-schedule signal delivery */
3637 sigprocmask(SIG_SETMASK, &omask, NULL);
3638 #endif
3639 }
3640 return (rv);
3641 }
3642 #endif
3643
3644 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
3645 static int
c_suspend(const char ** wp)3646 c_suspend(const char **wp)
3647 {
3648 if (wp[1] != NULL) {
3649 bi_errorf(Ttoo_many_args);
3650 return (1);
3651 }
3652 if (Flag(FLOGIN)) {
3653 /* Can't suspend an orphaned process group. */
3654 if (getpgid(kshppid) == getpgid(0) ||
3655 getsid(kshppid) != getsid(0)) {
3656 bi_errorf("can't suspend a login shell");
3657 return (1);
3658 }
3659 }
3660 j_suspend();
3661 return (0);
3662 }
3663 #endif
3664