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