c_ksh.c revision 1.24 1 /* $NetBSD: c_ksh.c,v 1.24 2017/06/22 19:41:07 kamil Exp $ */
2
3 /*
4 * built-in Korn commands: c_*
5 */
6 #include <sys/cdefs.h>
7
8 #ifndef lint
9 __RCSID("$NetBSD: c_ksh.c,v 1.24 2017/06/22 19:41:07 kamil Exp $");
10 #endif
11
12 #include "sh.h"
13 #include "ksh_stat.h"
14 #include <ctype.h>
15
16 int
17 c_cd(wp)
18 char **wp;
19 {
20 int optc;
21 int physical = Flag(FPHYSICAL);
22 int cdnode; /* was a node from cdpath added in? */
23 int printpath = 0; /* print where we cd'd? */
24 int rval;
25 struct tbl *pwd_s, *oldpwd_s;
26 XString xs;
27 char *xp;
28 char *dir, *try, *pwd;
29 int phys_path;
30 char *cdpath;
31 char *fdir = NULL;
32
33 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != EOF)
34 switch (optc) {
35 case 'L':
36 physical = 0;
37 break;
38 case 'P':
39 physical = 1;
40 break;
41 case '?':
42 return 1;
43 }
44 wp += builtin_opt.optind;
45
46 if (Flag(FRESTRICTED)) {
47 bi_errorf("restricted shell - can't cd");
48 return 1;
49 }
50
51 pwd_s = global("PWD");
52 oldpwd_s = global("OLDPWD");
53
54 if (!wp[0]) {
55 /* No arguments - go home */
56 if ((dir = str_val(global("HOME"))) == null) {
57 bi_errorf("no home directory (HOME not set)");
58 return 1;
59 }
60 } else if (!wp[1]) {
61 /* One argument: - or dir */
62 dir = wp[0];
63 if (strcmp(dir, "-") == 0) {
64 dir = str_val(oldpwd_s);
65 if (dir == null) {
66 bi_errorf("no OLDPWD");
67 return 1;
68 }
69 printpath++;
70 }
71 } else if (!wp[2]) {
72 /* Two arguments - substitute arg1 in PWD for arg2 */
73 int ilen, olen, nlen, elen;
74 char *cp;
75
76 if (!current_wd[0]) {
77 bi_errorf("don't know current directory");
78 return 1;
79 }
80 /* substitute arg1 for arg2 in current path.
81 * if the first substitution fails because the cd fails
82 * we could try to find another substitution. For now
83 * we don't
84 */
85 if ((cp = strstr(current_wd, wp[0])) == (char *) 0) {
86 bi_errorf("bad substitution");
87 return 1;
88 }
89 ilen = cp - current_wd;
90 olen = strlen(wp[0]);
91 nlen = strlen(wp[1]);
92 elen = strlen(current_wd + ilen + olen) + 1;
93 fdir = dir = alloc(ilen + nlen + elen, ATEMP);
94 memcpy(dir, current_wd, ilen);
95 memcpy(dir + ilen, wp[1], nlen);
96 memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
97 printpath++;
98 } else {
99 bi_errorf("too many arguments");
100 return 1;
101 }
102
103 Xinit(xs, xp, PATH, ATEMP);
104 /* xp will have a bogus value after make_path() - set it to 0
105 * so that if it's used, it will cause a dump
106 */
107 xp = (char *) 0;
108
109 cdpath = str_val(global("CDPATH"));
110 do {
111 cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
112 #ifdef S_ISLNK
113 if (physical)
114 rval = chdir(try = Xstring(xs, xp) + phys_path);
115 else
116 #endif /* S_ISLNK */
117 {
118 simplify_path(Xstring(xs, xp));
119 rval = chdir(try = Xstring(xs, xp));
120 }
121 } while (rval < 0 && cdpath != (char *) 0);
122
123 if (rval < 0) {
124 if (cdnode)
125 bi_errorf("%s: bad directory", dir);
126 else
127 bi_errorf("%s - %s", try, strerror(errno));
128 if (fdir)
129 afree(fdir, ATEMP);
130 return 1;
131 }
132
133 /* Clear out tracked aliases with relative paths */
134 flushcom(0);
135
136 /* Set OLDPWD (note: unsetting OLDPWD does not disable this
137 * setting in at&t ksh)
138 */
139 if (current_wd[0])
140 /* Ignore failure (happens if readonly or integer) */
141 setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
142
143 if (!ISABSPATH(Xstring(xs, xp))) {
144 pwd = (char *) 0;
145 } else
146 #ifdef S_ISLNK
147 if (!physical || !(pwd = get_phys_path(Xstring(xs, xp))))
148 #endif /* S_ISLNK */
149 pwd = Xstring(xs, xp);
150
151 /* Set PWD */
152 if (pwd) {
153 char *ptmp = pwd;
154 set_current_wd(ptmp);
155 /* Ignore failure (happens if readonly or integer) */
156 setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
157 } else {
158 set_current_wd(null);
159 pwd = Xstring(xs, xp);
160 /* XXX unset $PWD? */
161 }
162 if (printpath || cdnode)
163 shprintf("%s\n", pwd);
164
165 if (fdir)
166 afree(fdir, ATEMP);
167
168 return 0;
169 }
170
171 int
172 c_pwd(wp)
173 char **wp;
174 {
175 int optc;
176 int physical = Flag(FPHYSICAL);
177 char *p, *freep = NULL;
178
179 while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != EOF)
180 switch (optc) {
181 case 'L':
182 physical = 0;
183 break;
184 case 'P':
185 physical = 1;
186 break;
187 case '?':
188 return 1;
189 }
190 wp += builtin_opt.optind;
191
192 if (wp[0]) {
193 bi_errorf("too many arguments");
194 return 1;
195 }
196 #ifdef S_ISLNK
197 p = current_wd[0] ? (physical ? get_phys_path(current_wd) : current_wd)
198 : (char *) 0;
199 #else /* S_ISLNK */
200 p = current_wd[0] ? current_wd : (char *) 0;
201 #endif /* S_ISLNK */
202 if (p && eaccess(p, R_OK) < 0)
203 p = (char *) 0;
204 if (!p) {
205 freep = p = ksh_get_wd((char *) 0, 0);
206 if (!p) {
207 bi_errorf("can't get current directory - %s",
208 strerror(errno));
209 return 1;
210 }
211 }
212 shprintf("%s\n", p);
213 if (freep)
214 afree(freep, ATEMP);
215 return 0;
216 }
217
218 int
219 c_print(wp)
220 char **wp;
221 {
222 #define PO_NL BIT(0) /* print newline */
223 #define PO_EXPAND BIT(1) /* expand backslash sequences */
224 #define PO_PMINUSMINUS BIT(2) /* print a -- argument */
225 #define PO_HIST BIT(3) /* print to history instead of stdout */
226 #define PO_COPROC BIT(4) /* printing to coprocess: block SIGPIPE */
227 int fd = 1;
228 int flags = PO_EXPAND|PO_NL;
229 char *s;
230 const char *emsg;
231 XString xs;
232 char *xp;
233
234 if (wp[0][0] == 'e') { /* echo command */
235 int nflags = flags;
236
237 /* A compromise between sysV and BSD echo commands:
238 * escape sequences are enabled by default, and
239 * -n, -e and -E are recognized if they appear
240 * in arguments with no illegal options (ie, echo -nq
241 * will print -nq).
242 * Different from sysV echo since options are recognized,
243 * different from BSD echo since escape sequences are enabled
244 * by default.
245 */
246 wp += 1;
247 while ((s = *wp) && *s == '-' && s[1]) {
248 while (*++s)
249 if (*s == 'n')
250 nflags &= ~PO_NL;
251 else if (*s == 'e')
252 nflags |= PO_EXPAND;
253 else if (*s == 'E')
254 nflags &= ~PO_EXPAND;
255 else
256 /* bad option: don't use nflags, print
257 * argument
258 */
259 break;
260 if (*s)
261 break;
262 wp++;
263 flags = nflags;
264 }
265 } else {
266 int optc;
267 const char *options = "Rnprsu,";
268 while ((optc = ksh_getopt(wp, &builtin_opt, options)) != EOF)
269 switch (optc) {
270 case 'R': /* fake BSD echo command */
271 flags |= PO_PMINUSMINUS;
272 flags &= ~PO_EXPAND;
273 options = "ne";
274 break;
275 case 'e':
276 flags |= PO_EXPAND;
277 break;
278 case 'n':
279 flags &= ~PO_NL;
280 break;
281 #ifdef KSH
282 case 'p':
283 if ((fd = coproc_getfd(W_OK, &emsg)) < 0) {
284 bi_errorf("-p: %s", emsg);
285 return 1;
286 }
287 break;
288 #endif /* KSH */
289 case 'r':
290 flags &= ~PO_EXPAND;
291 break;
292 case 's':
293 flags |= PO_HIST;
294 break;
295 case 'u':
296 if (!*(s = builtin_opt.optarg))
297 fd = 0;
298 else if ((fd = check_fd(s, W_OK, &emsg)) < 0) {
299 bi_errorf("-u: %s: %s", s, emsg);
300 return 1;
301 }
302 break;
303 case '?':
304 return 1;
305 }
306 if (!(builtin_opt.info & GI_MINUSMINUS)) {
307 /* treat a lone - like -- */
308 if (wp[builtin_opt.optind]
309 && strcmp(wp[builtin_opt.optind], "-") == 0)
310 builtin_opt.optind++;
311 } else if (flags & PO_PMINUSMINUS)
312 builtin_opt.optind--;
313 wp += builtin_opt.optind;
314 }
315
316 Xinit(xs, xp, 128, ATEMP);
317
318 while (*wp != NULL) {
319 register int c;
320 s = *wp;
321 while ((c = *s++) != '\0') {
322 Xcheck(xs, xp);
323 if ((flags & PO_EXPAND) && c == '\\') {
324 int i;
325
326 switch ((c = *s++)) {
327 /* Oddly enough, \007 seems more portable than
328 * \a (due to old pcc's,
329 * etc.).
330 */
331 case 'a': c = '\007'; break;
332 case 'b': c = '\b'; break;
333 case 'c': flags &= ~PO_NL;
334 continue; /* AT&T brain damage */
335 case 'f': c = '\f'; break;
336 case 'n': c = '\n'; break;
337 case 'r': c = '\r'; break;
338 case 't': c = '\t'; break;
339 case 'v': c = 0x0B; break;
340 case '0':
341 /* Look for an octal number: can have
342 * three digits (not counting the
343 * leading 0). Truly burnt.
344 */
345 c = 0;
346 for (i = 0; i < 3; i++) {
347 if (*s >= '0' && *s <= '7')
348 c = c*8 + *s++ - '0';
349 else
350 break;
351 }
352 break;
353 case '\0': s--; c = '\\'; break;
354 case '\\': break;
355 default:
356 Xput(xs, xp, '\\');
357 }
358 }
359 Xput(xs, xp, c);
360 }
361 if (*++wp != NULL)
362 Xput(xs, xp, ' ');
363 }
364 if (flags & PO_NL)
365 Xput(xs, xp, '\n');
366
367 if (flags & PO_HIST) {
368 Xput(xs, xp, '\0');
369 source->line++;
370 histsave(source->line, Xstring(xs, xp), 1);
371 Xfree(xs, xp);
372 } else {
373 int n, len = Xlength(xs, xp);
374 int UNINITIALIZED(opipe);
375 #ifdef KSH
376
377 /* Ensure we aren't killed by a SIGPIPE while writing to
378 * a coprocess. at&t ksh doesn't seem to do this (seems
379 * to just check that the co-process is alive, which is
380 * not enough).
381 */
382 if (coproc.write >= 0 && coproc.write == fd) {
383 flags |= PO_COPROC;
384 opipe = block_pipe();
385 }
386 #endif /* KSH */
387 for (s = Xstring(xs, xp); len > 0; ) {
388 n = write(fd, s, len);
389 if (n < 0) {
390 #ifdef KSH
391 if (flags & PO_COPROC)
392 restore_pipe(opipe);
393 #endif /* KSH */
394 if (errno == EINTR) {
395 /* allow user to ^C out */
396 intrcheck();
397 #ifdef KSH
398 if (flags & PO_COPROC)
399 opipe = block_pipe();
400 #endif /* KSH */
401 continue;
402 }
403 #ifdef KSH
404 /* This doesn't really make sense - could
405 * break scripts (print -p generates
406 * error message).
407 *if (errno == EPIPE)
408 * coproc_write_close(fd);
409 */
410 #endif /* KSH */
411 return 1;
412 }
413 s += n;
414 len -= n;
415 }
416 #ifdef KSH
417 if (flags & PO_COPROC)
418 restore_pipe(opipe);
419 #endif /* KSH */
420 }
421
422 return 0;
423 }
424
425 int
426 c_whence(wp)
427 char **wp;
428 {
429 struct tbl *tp;
430 char *id;
431 int pflag = 0, vflag = 0, Vflag = 0;
432 int ret = 0;
433 int optc;
434 int iam_whence = wp[0][0] == 'w';
435 int fcflags;
436 const char *options = iam_whence ? "pv" : "pvV";
437
438 while ((optc = ksh_getopt(wp, &builtin_opt, options)) != EOF)
439 switch (optc) {
440 case 'p':
441 pflag = 1;
442 break;
443 case 'v':
444 vflag = 1;
445 break;
446 case 'V':
447 Vflag = 1;
448 break;
449 case '?':
450 return 1;
451 }
452 wp += builtin_opt.optind;
453
454
455 fcflags = FC_BI | FC_PATH | FC_FUNC;
456 if (!iam_whence) {
457 /* Note that -p on its own is deal with in comexec() */
458 if (pflag)
459 fcflags |= FC_DEFPATH;
460 /* Convert command options to whence options - note that
461 * command -pV uses a different path search than whence -v
462 * or whence -pv. This should be considered a feature.
463 */
464 vflag = Vflag;
465 }
466 if (pflag)
467 fcflags &= ~(FC_BI | FC_FUNC);
468
469 while ((vflag || ret == 0) && (id = *wp++) != NULL) {
470 tp = NULL;
471 if ((iam_whence || vflag) && !pflag)
472 tp = tsearch(&keywords, id, hash(id));
473 if (!tp && !pflag) {
474 tp = tsearch(&aliases, id, hash(id));
475 if (tp && !(tp->flag & ISSET))
476 tp = NULL;
477 }
478 if (!tp)
479 tp = findcom(id, fcflags);
480 if (vflag || (tp->type != CALIAS && tp->type != CEXEC
481 && tp->type != CTALIAS))
482 shprintf("%s", id);
483 switch (tp->type) {
484 case CKEYWD:
485 if (vflag)
486 shprintf(" is a reserved word");
487 break;
488 case CALIAS:
489 if (vflag)
490 shprintf(" is an %salias for ",
491 (tp->flag & EXPORT) ? "exported "
492 : null);
493 if (!iam_whence && !vflag)
494 shprintf("alias %s=", id);
495 print_value_quoted(tp->val.s);
496 break;
497 case CFUNC:
498 if (vflag) {
499 shprintf(" is a");
500 if (tp->flag & EXPORT)
501 shprintf("n exported");
502 if (tp->flag & TRACE)
503 shprintf(" traced");
504 if (!(tp->flag & ISSET)) {
505 shprintf(" undefined");
506 if (tp->u.fpath)
507 shprintf(" (autoload from %s)",
508 tp->u.fpath);
509 }
510 shprintf(" function");
511 }
512 break;
513 case CSHELL:
514 if (vflag)
515 shprintf(" is a%s shell builtin",
516 (tp->flag & SPEC_BI) ? " special" : null);
517 break;
518 case CTALIAS:
519 case CEXEC:
520 if (tp->flag & ISSET) {
521 if (vflag) {
522 shprintf(" is ");
523 if (tp->type == CTALIAS)
524 shprintf(
525 "a tracked %salias for ",
526 (tp->flag & EXPORT) ?
527 "exported "
528 : null);
529 }
530 shprintf("%s", tp->val.s);
531 } else {
532 if (vflag)
533 shprintf(" not found");
534 ret = 1;
535 }
536 break;
537 default:
538 shprintf("%s is *GOK*", id);
539 break;
540 }
541 if (vflag || !ret)
542 shprintf("%s", newline);
543 }
544 return ret;
545 }
546
547 /* Deal with command -vV - command -p dealt with in comexec() */
548 int
549 c_command(wp)
550 char **wp;
551 {
552 /* Let c_whence do the work. Note that c_command() must be
553 * a distinct function from c_whence() (tested in comexec()).
554 */
555 return c_whence(wp);
556 }
557
558 /* typeset, export, and readonly */
559 int
560 c_typeset(wp)
561 char **wp;
562 {
563 struct block *l = e->loc;
564 struct tbl *vp, **p;
565 Tflag fset = 0, fclr = 0;
566 int thing = 0, func = 0, localv = 0;
567 const char *options = "L#R#UZ#fi#lprtux"; /* see comment below */
568 char *fieldstr, *basestr;
569 int field, base;
570 int optc;
571 Tflag flag;
572 int pflag = 0;
573
574 switch (**wp) {
575 case 'e': /* export */
576 fset |= EXPORT;
577 options = "p";
578 break;
579 case 'r': /* readonly */
580 fset |= RDONLY;
581 options = "p";
582 break;
583 case 's': /* set */
584 /* called with 'typeset -' */
585 break;
586 case 't': /* typeset */
587 localv = 1;
588 break;
589 }
590
591 fieldstr = basestr = (char *) 0;
592 builtin_opt.flags |= GF_PLUSOPT;
593 /* at&t ksh seems to have 0-9 as options, which are multiplied
594 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
595 * sets right justify in a field of 12). This allows options
596 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
597 * does not allow the number to be specified as a separate argument
598 * Here, the number must follow the RLZi option, but is optional
599 * (see the # kludge in ksh_getopt()).
600 */
601 while ((optc = ksh_getopt(wp, &builtin_opt, options)) != EOF) {
602 flag = 0;
603 switch (optc) {
604 case 'L':
605 flag = LJUST;
606 fieldstr = builtin_opt.optarg;
607 break;
608 case 'R':
609 flag = RJUST;
610 fieldstr = builtin_opt.optarg;
611 break;
612 case 'U':
613 /* at&t ksh uses u, but this conflicts with
614 * upper/lower case. If this option is changed,
615 * need to change the -U below as well
616 */
617 flag = INT_U;
618 break;
619 case 'Z':
620 flag = ZEROFIL;
621 fieldstr = builtin_opt.optarg;
622 break;
623 case 'f':
624 func = 1;
625 break;
626 case 'i':
627 flag = INTEGER;
628 basestr = builtin_opt.optarg;
629 break;
630 case 'l':
631 flag = LCASEV;
632 break;
633 case 'p': /* posix export/readonly -p flag.
634 * typeset -p is the same as typeset (in pdksh);
635 * here for compatibility with ksh93.
636 */
637 pflag = 1;
638 break;
639 case 'r':
640 flag = RDONLY;
641 break;
642 case 't':
643 flag = TRACE;
644 break;
645 case 'u':
646 flag = UCASEV_AL; /* upper case / autoload */
647 break;
648 case 'x':
649 flag = EXPORT;
650 break;
651 case '?':
652 return 1;
653 }
654 if (builtin_opt.info & GI_PLUS) {
655 fclr |= flag;
656 fset &= ~flag;
657 thing = '+';
658 } else {
659 fset |= flag;
660 fclr &= ~flag;
661 thing = '-';
662 }
663 }
664
665 field = 0;
666 if (fieldstr && !bi_getn(fieldstr, &field))
667 return 1;
668 base = 0;
669 if (basestr && !bi_getn(basestr, &base))
670 return 1;
671
672 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind]
673 && (wp[builtin_opt.optind][0] == '-'
674 || wp[builtin_opt.optind][0] == '+')
675 && wp[builtin_opt.optind][1] == '\0')
676 {
677 thing = wp[builtin_opt.optind][0];
678 builtin_opt.optind++;
679 }
680
681 if (func && ((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT))) {
682 bi_errorf("only -t, -u and -x options may be used with -f");
683 return 1;
684 }
685 if (wp[builtin_opt.optind]) {
686 /* Take care of exclusions.
687 * At this point, flags in fset are cleared in fclr and vise
688 * versa. This property should be preserved.
689 */
690 if (fset & LCASEV) /* LCASEV has priority over UCASEV_AL */
691 fset &= ~UCASEV_AL;
692 if (fset & LJUST) /* LJUST has priority over RJUST */
693 fset &= ~RJUST;
694 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) { /* -Z implies -ZR */
695 fset |= RJUST;
696 fclr &= ~RJUST;
697 }
698 /* Setting these attributes clears the others, unless they
699 * are also set in this command
700 */
701 if (fset & (LJUST|RJUST|ZEROFIL|UCASEV_AL|LCASEV|INTEGER
702 |INT_U|INT_L))
703 fclr |= ~fset &
704 (LJUST|RJUST|ZEROFIL|UCASEV_AL|LCASEV|INTEGER
705 |INT_U|INT_L);
706 }
707
708 /* set variables and attributes */
709 if (wp[builtin_opt.optind]) {
710 int i;
711 int rval = 0;
712 struct tbl *f;
713
714 if (localv && !func)
715 fset |= LOCAL;
716 for (i = builtin_opt.optind; wp[i]; i++) {
717 if (func) {
718 f = findfunc(wp[i], hash(wp[i]),
719 (fset&UCASEV_AL) ? TRUE : FALSE);
720 if (!f) {
721 /* at&t ksh does ++rval: bogus */
722 rval = 1;
723 continue;
724 }
725 if (fset | fclr) {
726 f->flag |= fset;
727 f->flag &= ~fclr;
728 } else
729 fptreef(shl_stdout, 0,
730 f->flag & FKSH ?
731 "function %s %T\n"
732 : "%s() %T\n"
733 ,
734 wp[i], f->val.t);
735 } else if (!typeset(wp[i], fset, fclr, field, base)) {
736 bi_errorf("%s: not identifier", wp[i]);
737 return 1;
738 }
739 }
740 return rval;
741 }
742
743 /* list variables and attributes */
744 flag = fset | fclr; /* no difference at this point.. */
745 if (func) {
746 for (l = e->loc; l; l = l->next) {
747 for (p = tsort(&l->funs); (vp = *p++); ) {
748 if (flag && (vp->flag & flag) == 0)
749 continue;
750 if (thing == '-')
751 fptreef(shl_stdout, 0, vp->flag & FKSH ?
752 "function %s %T\n"
753 : "%s() %T\n",
754 vp->name, vp->val.t);
755 else
756 shprintf("%s\n", vp->name);
757 }
758 }
759 } else {
760 for (l = e->loc; l; l = l->next) {
761 for (p = tsort(&l->vars); (vp = *p++); ) {
762 struct tbl *tvp;
763 int any_set = 0;
764 /*
765 * See if the parameter is set (for arrays, if any
766 * element is set).
767 */
768 for (tvp = vp; tvp; tvp = tvp->u.array)
769 if (tvp->flag & ISSET) {
770 any_set = 1;
771 break;
772 }
773 /*
774 * Check attributes - note that all array elements
775 * have (should have?) the same attributes, so checking
776 * the first is sufficient.
777 *
778 * Report an unset param only if the user has
779 * explicitly given it some attribute (like export);
780 * otherwise, after "echo $FOO", we would report FOO...
781 */
782 if (!any_set && !(vp->flag & USERATTRIB))
783 continue;
784 if (flag && (vp->flag & flag) == 0)
785 continue;
786 for (; vp; vp = vp->u.array) {
787 /* Ignore array elements that aren't set unless there
788 * are no set elements, in which case the first is
789 * reported on
790 */
791 if ((vp->flag&ARRAY) && any_set && !(vp->flag & ISSET))
792 continue;
793 /* no arguments */
794 if (thing == 0 && flag == 0) {
795 /* at&t ksh prints things like export, integer,
796 * leftadj, zerofill, etc., but POSIX says must
797 * be suitable for re-entry...
798 */
799 shprintf("typeset ");
800 if ((vp->flag&INTEGER))
801 shprintf("-i ");
802 if ((vp->flag&EXPORT))
803 shprintf("-x ");
804 if ((vp->flag&RDONLY))
805 shprintf("-r ");
806 if ((vp->flag&TRACE))
807 shprintf("-t ");
808 if ((vp->flag&LJUST))
809 shprintf("-L%d ", vp->u2.field);
810 if ((vp->flag&RJUST))
811 shprintf("-R%d ", vp->u2.field);
812 if ((vp->flag&ZEROFIL))
813 shprintf("-Z ");
814 if ((vp->flag&LCASEV))
815 shprintf("-l ");
816 if ((vp->flag&UCASEV_AL))
817 shprintf("-u ");
818 if ((vp->flag&INT_U))
819 shprintf("-U ");
820 shprintf("%s\n", vp->name);
821 if (vp->flag&ARRAY)
822 break;
823 } else {
824 if (pflag)
825 shprintf("%s ",
826 (flag & EXPORT) ? "export" : "readonly");
827 if ((vp->flag&ARRAY) && any_set)
828 shprintf("%s[%d]", vp->name, vp->index);
829 else
830 shprintf("%s", vp->name);
831 if (thing == '-' && (vp->flag&ISSET)) {
832 char *s = str_val(vp);
833
834 shprintf("=");
835 /* at&t ksh can't have justified integers.. */
836 if ((vp->flag & (INTEGER|LJUST|RJUST))
837 == INTEGER)
838 shprintf("%s", s);
839 else
840 print_value_quoted(s);
841 }
842 shprintf("%s", newline);
843 }
844 /* Only report first `element' of an array with
845 * no set elements.
846 */
847 if (!any_set)
848 break;
849 }
850 }
851 }
852 }
853 return 0;
854 }
855
856 int
857 c_alias(wp)
858 char **wp;
859 {
860 struct table *t = &aliases;
861 int rv = 0, rflag = 0, tflag, Uflag = 0, pflag = 0;
862 int prefix = 0;
863 Tflag xflag = 0;
864 int optc;
865
866 builtin_opt.flags |= GF_PLUSOPT;
867 while ((optc = ksh_getopt(wp, &builtin_opt, "dprtUx")) != EOF) {
868 prefix = builtin_opt.info & GI_PLUS ? '+' : '-';
869 switch (optc) {
870 case 'd':
871 t = &homedirs;
872 break;
873 case 'p':
874 pflag = 1;
875 break;
876 case 'r':
877 rflag = 1;
878 break;
879 case 't':
880 t = &taliases;
881 break;
882 case 'U': /* kludge for tracked alias initialization
883 * (don't do a path search, just make an entry)
884 */
885 Uflag = 1;
886 break;
887 case 'x':
888 xflag = EXPORT;
889 break;
890 case '?':
891 return 1;
892 }
893 }
894 wp += builtin_opt.optind;
895
896 if (!(builtin_opt.info & GI_MINUSMINUS) && *wp
897 && (wp[0][0] == '-' || wp[0][0] == '+') && wp[0][1] == '\0')
898 {
899 prefix = wp[0][0];
900 wp++;
901 }
902
903 tflag = t == &taliases;
904
905 /* "hash -r" means reset all the tracked aliases.. */
906 if (rflag) {
907 static const char *const args[] = {
908 "unalias", "-ta", (const char *) 0
909 };
910
911 if (!tflag || *wp) {
912 shprintf(
913 "alias: -r flag can only be used with -t and without arguments\n");
914 return 1;
915 }
916 ksh_getopt_reset(&builtin_opt, GF_ERROR);
917 return c_unalias((char **)__UNCONST(args));
918 }
919
920
921 if (*wp == NULL) {
922 struct tbl *ap, **p;
923
924 for (p = tsort(t); (ap = *p++) != NULL; )
925 if ((ap->flag & (ISSET|xflag)) == (ISSET|xflag)) {
926 if (pflag)
927 shf_puts("alias ", shl_stdout);
928 shf_puts(ap->name, shl_stdout);
929 if (prefix != '+') {
930 shf_putc('=', shl_stdout);
931 print_value_quoted(ap->val.s);
932 }
933 shprintf("%s", newline);
934 }
935 }
936
937 for (; *wp != NULL; wp++) {
938 char *alias = *wp;
939 char *val = strchr(alias, '=');
940 char *newval;
941 struct tbl *ap;
942 int h;
943
944 if (val)
945 alias = str_nsave(alias, val++ - alias, ATEMP);
946 h = hash(alias);
947 if (val == NULL && !tflag && !xflag) {
948 ap = tsearch(t, alias, h);
949 if (ap != NULL && (ap->flag&ISSET)) {
950 if (pflag)
951 shf_puts("alias ", shl_stdout);
952 shf_puts(ap->name, shl_stdout);
953 if (prefix != '+') {
954 shf_putc('=', shl_stdout);
955 print_value_quoted(ap->val.s);
956 }
957 shprintf("%s", newline);
958 } else {
959 shprintf("%s alias not found\n", alias);
960 rv = 1;
961 }
962 continue;
963 }
964 ap = tenter(t, alias, h);
965 ap->type = tflag ? CTALIAS : CALIAS;
966 /* Are we setting the value or just some flags? */
967 if ((val && !tflag) || (!val && tflag && !Uflag)) {
968 if (ap->flag&ALLOC) {
969 ap->flag &= ~(ALLOC|ISSET);
970 afree((void*)ap->val.s, APERM);
971 }
972 /* ignore values for -t (at&t ksh does this) */
973 newval = tflag ? search(alias, path, X_OK, (int *) 0)
974 : val;
975 if (newval) {
976 ap->val.s = str_save(newval, APERM);
977 ap->flag |= ALLOC|ISSET;
978 } else
979 ap->flag &= ~ISSET;
980 }
981 ap->flag |= DEFINED;
982 if (prefix == '+')
983 ap->flag &= ~xflag;
984 else
985 ap->flag |= xflag;
986 if (val)
987 afree(alias, ATEMP);
988 }
989
990 return rv;
991 }
992
993 int
994 c_unalias(wp)
995 char **wp;
996 {
997 register struct table *t = &aliases;
998 register struct tbl *ap;
999 int rv = 0, all = 0;
1000 int optc;
1001
1002 while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != EOF)
1003 switch (optc) {
1004 case 'a':
1005 all = 1;
1006 break;
1007 case 'd':
1008 t = &homedirs;
1009 break;
1010 case 't':
1011 t = &taliases;
1012 break;
1013 case '?':
1014 return 1;
1015 }
1016 wp += builtin_opt.optind;
1017
1018 for (; *wp != NULL; wp++) {
1019 ap = tsearch(t, *wp, hash(*wp));
1020 if (ap == NULL) {
1021 rv = 1; /* POSIX */
1022 continue;
1023 }
1024 if (ap->flag&ALLOC) {
1025 ap->flag &= ~(ALLOC|ISSET);
1026 afree((void*)ap->val.s, APERM);
1027 }
1028 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1029 }
1030
1031 if (all) {
1032 struct tstate ts;
1033
1034 for (twalk(&ts, t); (ap = tnext(&ts)); ) {
1035 if (ap->flag&ALLOC) {
1036 ap->flag &= ~(ALLOC|ISSET);
1037 afree((void*)ap->val.s, APERM);
1038 }
1039 ap->flag &= ~(DEFINED|ISSET|EXPORT);
1040 }
1041 }
1042
1043 return rv;
1044 }
1045
1046 #ifdef KSH
1047 int
1048 c_let(wp)
1049 char **wp;
1050 {
1051 int rv = 1;
1052 long val;
1053
1054 if (wp[1] == (char *) 0) /* at&t ksh does this */
1055 bi_errorf("no arguments");
1056 else
1057 for (wp++; *wp; wp++)
1058 if (!evaluate(*wp, &val, KSH_RETURN_ERROR)) {
1059 rv = 2; /* distinguish error from zero result */
1060 break;
1061 } else
1062 rv = val == 0;
1063 return rv;
1064 }
1065 #endif /* KSH */
1066
1067 int
1068 c_jobs(wp)
1069 char **wp;
1070 {
1071 int optc;
1072 int flag = 0;
1073 int nflag = 0;
1074 int rv = 0;
1075
1076 while ((optc = ksh_getopt(wp, &builtin_opt, "lpnz")) != EOF)
1077 switch (optc) {
1078 case 'l':
1079 flag = 1;
1080 break;
1081 case 'p':
1082 flag = 2;
1083 break;
1084 case 'n':
1085 nflag = 1;
1086 break;
1087 case 'z': /* debugging: print zombies */
1088 nflag = -1;
1089 break;
1090 case '?':
1091 return 1;
1092 }
1093 wp += builtin_opt.optind;
1094 if (!*wp) {
1095 if (j_jobs((char *) 0, flag, nflag))
1096 rv = 1;
1097 } else {
1098 for (; *wp; wp++)
1099 if (j_jobs(*wp, flag, nflag))
1100 rv = 1;
1101 }
1102 return rv;
1103 }
1104
1105 #ifdef JOBS
1106 int
1107 c_fgbg(wp)
1108 char **wp;
1109 {
1110 int bg = strcmp(*wp, "bg") == 0;
1111 int UNINITIALIZED(rv);
1112
1113 if (!Flag(FMONITOR)) {
1114 bi_errorf("job control not enabled");
1115 return 1;
1116 }
1117 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1118 return 1;
1119 wp += builtin_opt.optind;
1120 if (*wp)
1121 for (; *wp; wp++)
1122 rv = j_resume(*wp, bg);
1123 else
1124 rv = j_resume("%%", bg);
1125 /* POSIX says fg shall return 0 (unless an error occurs).
1126 * at&t ksh returns the exit value of the job...
1127 */
1128 return (bg || Flag(FPOSIX)) ? 0 : rv;
1129 }
1130 #endif
1131
1132 struct kill_info {
1133 int num_width;
1134 int name_width;
1135 };
1136 static char *kill_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
1137
1138 /* format a single kill item */
1139 static char *
1140 kill_fmt_entry(arg, i, buf, buflen)
1141 void *arg;
1142 int i;
1143 char *buf;
1144 int buflen;
1145 {
1146 struct kill_info *ki = (struct kill_info *) arg;
1147
1148 i++;
1149 if (sigtraps[i].name)
1150 shf_snprintf(buf, buflen, "%*d %*s %s",
1151 ki->num_width, i,
1152 ki->name_width, sigtraps[i].name,
1153 sigtraps[i].mess);
1154 else
1155 shf_snprintf(buf, buflen, "%*d %*d %s",
1156 ki->num_width, i,
1157 ki->name_width, sigtraps[i].signal,
1158 sigtraps[i].mess);
1159 return buf;
1160 }
1161
1162
1163 int
1164 c_kill(wp)
1165 char **wp;
1166 {
1167 Trap *t = (Trap *) 0;
1168 char *p;
1169 int lflag = 0;
1170 int i, n, rv, sig;
1171
1172 /* assume old style options if -digits or -UPPERCASE */
1173 if ((p = wp[1]) && *p == '-'
1174 && (digit(p[1]) || isupper((unsigned char)p[1]))) {
1175 if (!(t = gettrap(p + 1, TRUE))) {
1176 bi_errorf("bad signal `%s'", p + 1);
1177 return 1;
1178 }
1179 i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
1180 } else {
1181 int optc;
1182
1183 while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != EOF)
1184 switch (optc) {
1185 case 'l':
1186 lflag = 1;
1187 break;
1188 case 's':
1189 if (!(t = gettrap(builtin_opt.optarg, TRUE))) {
1190 bi_errorf("bad signal `%s'",
1191 builtin_opt.optarg);
1192 return 1;
1193 }
1194 break;
1195 case '?':
1196 return 1;
1197 }
1198 i = builtin_opt.optind;
1199 }
1200 if ((lflag && t) || (!wp[i] && !lflag)) {
1201 shf_fprintf(shl_out,
1202 "usage: kill [ -s signame | -signum | -signame ] {pid|job}...\n\
1203 kill -l [exit_status]\n"
1204 );
1205 bi_errorf("%s", null);
1206 return 1;
1207 }
1208
1209 if (lflag) {
1210 if (wp[i]) {
1211 for (; wp[i]; i++) {
1212 if (!bi_getn(wp[i], &n))
1213 return 1;
1214 if (n > 128 && n < 128 + SIGNALS)
1215 n -= 128;
1216 if (n > 0 && n < SIGNALS && sigtraps[n].name)
1217 shprintf("%s\n", sigtraps[n].name);
1218 else
1219 shprintf("%d\n", n);
1220 }
1221 } else if (Flag(FPOSIX)) {
1222 p = null;
1223 for (i = 1; i < SIGNALS; i++, p = space)
1224 if (sigtraps[i].name)
1225 shprintf("%s%s", p, sigtraps[i].name);
1226 shprintf("%s", newline);
1227 } else {
1228 int w, si;
1229 int mess_width;
1230 struct kill_info ki;
1231
1232 for (si = SIGNALS, ki.num_width = 1; si >= 10; si /= 10)
1233 ki.num_width++;
1234 ki.name_width = mess_width = 0;
1235 for (si = 0; si < SIGNALS; si++) {
1236 w = sigtraps[si].name ?
1237 (int)strlen(sigtraps[si].name) :
1238 ki.num_width;
1239 if (w > ki.name_width)
1240 ki.name_width = w;
1241 w = strlen(sigtraps[si].mess);
1242 if (w > mess_width)
1243 mess_width = w;
1244 }
1245
1246 print_columns(shl_stdout, SIGNALS - 1,
1247 kill_fmt_entry, (void *) &ki,
1248 ki.num_width + ki.name_width + mess_width + 3, 1);
1249 }
1250 return 0;
1251 }
1252 rv = 0;
1253 sig = t ? t->signal : SIGTERM;
1254 for (; (p = wp[i]); i++) {
1255 if (*p == '%') {
1256 if (j_kill(p, sig))
1257 rv = 1;
1258 } else if (!getn(p, &n)) {
1259 bi_errorf("%s: arguments must be jobs or process IDs",
1260 p);
1261 rv = 1;
1262 } else {
1263 /* use killpg if < -1 since -1 does special things for
1264 * some non-killpg-endowed kills
1265 */
1266 if ((n < -1 ? killpg(-n, sig) : kill(n, sig)) < 0) {
1267 bi_errorf("%s: %s", p, strerror(errno));
1268 rv = 1;
1269 }
1270 }
1271 }
1272 return rv;
1273 }
1274
1275 void
1276 getopts_reset(val)
1277 int val;
1278 {
1279 if (val >= 1) {
1280 ksh_getopt_reset(&user_opt,
1281 GF_NONAME | (Flag(FPOSIX) ? 0 : GF_PLUSOPT));
1282 user_opt.optind = user_opt.uoptind = val;
1283 }
1284 }
1285
1286 int
1287 c_getopts(wp)
1288 char **wp;
1289 {
1290 int argc;
1291 const char *options;
1292 const char *var;
1293 int optc;
1294 int ret;
1295 char buf[3];
1296 struct tbl *vq, *voptarg;
1297
1298 if (ksh_getopt(wp, &builtin_opt, null) == '?')
1299 return 1;
1300 wp += builtin_opt.optind;
1301
1302 options = *wp++;
1303 if (!options) {
1304 bi_errorf("missing options argument");
1305 return 1;
1306 }
1307
1308 var = *wp++;
1309 if (!var) {
1310 bi_errorf("missing name argument");
1311 return 1;
1312 }
1313 if (!*var || *skip_varname(var, TRUE)) {
1314 bi_errorf("%s: is not an identifier", var);
1315 return 1;
1316 }
1317
1318 if (e->loc->next == (struct block *) 0) {
1319 internal_errorf(0, "c_getopts: no argv");
1320 return 1;
1321 }
1322 /* Which arguments are we parsing... */
1323 if (*wp == (char *) 0)
1324 wp = e->loc->next->argv;
1325 else
1326 *--wp = e->loc->next->argv[0];
1327
1328 /* Check that our saved state won't cause a core dump... */
1329 for (argc = 0; wp[argc]; argc++)
1330 ;
1331 if (user_opt.optind > argc
1332 || (user_opt.p != 0
1333 && user_opt.p > strlen(wp[user_opt.optind - 1])))
1334 {
1335 bi_errorf("arguments changed since last call");
1336 return 1;
1337 }
1338
1339 user_opt.optarg = (char *) 0;
1340 optc = ksh_getopt(wp, &user_opt, options);
1341
1342 if (optc >= 0 && optc != '?' && (user_opt.info & GI_PLUS)) {
1343 buf[0] = '+';
1344 buf[1] = optc;
1345 buf[2] = '\0';
1346 } else {
1347 /* POSIX says var is set to ? at end-of-options, at&t ksh
1348 * sets it to null - we go with POSIX...
1349 */
1350 buf[0] = optc < 0 ? '?' : optc;
1351 buf[1] = '\0';
1352 }
1353
1354 /* at&t ksh does not change OPTIND if it was an unknown option.
1355 * Scripts counting on this are prone to break... (ie, don't count
1356 * on this staying).
1357 */
1358 if (optc != '?') {
1359 user_opt.uoptind = user_opt.optind;
1360 }
1361
1362 voptarg = global("OPTARG");
1363 voptarg->flag &= ~RDONLY; /* at&t ksh clears ro and int */
1364 /* Paranoia: ensure no bizarre results. */
1365 if (voptarg->flag & INTEGER)
1366 typeset("OPTARG", 0, INTEGER, 0, 0);
1367 if (user_opt.optarg == (char *) 0)
1368 unset(voptarg, 0);
1369 else
1370 /* This can't fail (have cleared readonly/integer) */
1371 setstr(voptarg, user_opt.optarg, KSH_RETURN_ERROR);
1372
1373 ret = 0;
1374
1375 vq = global(var);
1376 /* Error message already printed (integer, readonly) */
1377 if (!setstr(vq, buf, KSH_RETURN_ERROR))
1378 ret = 1;
1379 if (Flag(FEXPORT))
1380 typeset(var, EXPORT, 0, 0, 0);
1381
1382 return optc < 0 ? 1 : ret;
1383 }
1384
1385 #ifdef EMACS
1386 int
1387 c_bind(wp)
1388 char **wp;
1389 {
1390 int rv = 0, macro = 0, list = 0;
1391 register char *cp;
1392 int optc;
1393
1394 while ((optc = ksh_getopt(wp, &builtin_opt, "lm")) != EOF)
1395 switch (optc) {
1396 case 'l':
1397 list = 1;
1398 break;
1399 case 'm':
1400 macro = 1;
1401 break;
1402 case '?':
1403 return 1;
1404 }
1405 wp += builtin_opt.optind;
1406
1407 if (*wp == NULL) /* list all */
1408 rv = x_bind(NULL, NULL, 0, list);
1409
1410 for (; *wp != NULL; wp++) {
1411 cp = strchr(*wp, '=');
1412 if (cp != NULL)
1413 *cp++ = '\0';
1414 if (x_bind(*wp, cp, macro, 0))
1415 rv = 1;
1416 }
1417
1418 return rv;
1419 }
1420 #endif
1421
1422 /* A leading = means assignments before command are kept;
1423 * a leading * means a POSIX special builtin;
1424 * a leading + means a POSIX regular builtin
1425 * (* and + should not be combined).
1426 */
1427 const struct builtin kshbuiltins [] = {
1428 {"+alias", c_alias}, /* no =: at&t manual wrong */
1429 {"+cd", c_cd},
1430 {"+command", c_command},
1431 {"echo", c_print},
1432 {"*=export", c_typeset},
1433 #ifdef HISTORY
1434 {"+fc", c_fc},
1435 #endif /* HISTORY */
1436 {"+getopts", c_getopts},
1437 {"+jobs", c_jobs},
1438 {"+kill", c_kill},
1439 #ifdef KSH
1440 {"let", c_let},
1441 #endif /* KSH */
1442 {"print", c_print},
1443 {"pwd", c_pwd},
1444 {"*=readonly", c_typeset},
1445 {"=typeset", c_typeset},
1446 {"+unalias", c_unalias},
1447 {"whence", c_whence},
1448 #ifdef JOBS
1449 {"+bg", c_fgbg},
1450 {"+fg", c_fgbg},
1451 #endif
1452 #ifdef EMACS
1453 {"bind", c_bind},
1454 #endif
1455 {NULL, NULL}
1456 };
1457